Here’s an example of a piecewise function with 3 "pieces" (or "conditions"):
# species-dot :: (Row) -> Image
fun species-dot(r):
if (r["species"] == "dog"): square(5, "solid", "black")
else if (r["species"] == "cat"): square(5, "solid", "orange")
else if (r["species"] == "lizard"): square(5, "solid", "green")
end
end
What do you Notice about this code? | What do you Wonder? |
---|---|
1 What will this function produce for a dog?
2 What will this function produce for a cat?
Open the Piecewise Displays Starter File, and click "Run".
3 Compare the regular scatter plot with the image scatter plot. What can you see now that you couldn’t see before?
4 Compare the regular histogram with the image histogram. What can you see now that you couldn’t see before?
5 What do you think will happen if we run the function on a species that it has no condition for?
6 On line 45, add a comment (#
) to "turn off" the condition for snails. Click Run and test your prediction. In your own words, describe how piecewise / conditional functions work.
★
Make a new function (don’t delete species-dot
!), which uses piecewise functions to draw something different! For example, have it draw different shapes depending on whether an animal is younger than 3 years old or not.
These materials were developed partly through support of the National Science Foundation, (awards 1042210, 1535276, 1648684, 1738598, 2031479, and 1501927). Bootstrap by the Bootstrap Community is licensed under a Creative Commons 4.0 Unported License. This license does not grant permission to run training or professional development. Offering training or professional development with materials substantially derived from Bootstrap must be approved in writing by a Bootstrap Director. Permissions beyond the scope of this license, such as to run training, may be available by contacting contact@BootstrapWorld.org.