Functions: Basics

Learn functions with Elm!


Objectives of this tutorial:
1.	Learn to use functions

1. Now that you have made some shapes, we can try to apply functions to them. Click on the blank code page link: 
A)	Copy-Paste this code:
import Color exposing (..)
import Graphics.Collage exposing (..)

main = collage 300 300 
       [ (heart) ]

heart = group [ move (0,0) (filled red (ngon 4 50))
                  , move (20,20) (filled red (circle 36))
                  , move (-20,20) (filled red (circle 36))] 
B)	You can replace the heart shape with your own shape if you want. 
	To do this:
	i)  Change the group of shapes that make up the heart to your own set of shapes
      ii) Name your new shape and reference it in the collage [ (heart) ]
C)	Now we can create a User-Defined function (a custom function) in order to double the size of our shape! To create a custom function, we follow this syntax:
functionName parameter = …  
- functionName This can be any name that you want to call the function
- parameter This represents the condition or the value you would want to change.
>> Try to create a function that will return double the parameter value. You may type this new code right under the rest of the code. 

Answer >> double n = 2*n  

D)	Now we apply this function to a number. Since we are trying to double the size of the shape, we will apply double to a number n, inside the function scale _ _ , which is a Built-In function that takes a number and a shape as its parameters. For example: scale (2) (filled red (circle 5))

Answer >> Change  [(heart)]  to [scale (double 1) (heart)]
(The reason it is “scale (double 1) (heart)” is because a shape (heart) scaled to size “1” is normal size. So applying the double function does 2*(1) = 2, which is 2 times the size.

>> You can use the double function to double any number you want! If you just wanted to double the size of one of the shapes in the group of shapes, try this for the heart example above:
(filled red (circle (double 36)).
BONUS: Try changing the double function to halve the size instead! 

Previous Tutorial Back to Tutorials Next Tutorial