Haskell Functions
A function is a named rule that turns an input into a result. You write the rule once and call it many times.
double doubles its input
The definition names the input x. The body multiplies that input by 2.
double x = x * 2
main :: IO ()
main = print (double 4)A function can build text
This function takes a name as its input. Its body joins a greeting to that name.
greet name = "Hello, " ++ name
main :: IO ()
main = putStrLn (greet "Ana")One definition serves many calls
The same definition is called twice here. Each call uses a different input.
double x = x * 2
main :: IO ()
main = print (double 3 + double 5)Example
double x = x * 2
quadruple x = double (double x)
main :: IO ()
main = print (quadruple 3)Key points
- Definition: a function definition gives a name to a rule.
- Input: an input is a value the function works on.
- Result: the result is the value the rule produces.
- Call: a call writes the function name followed by the input.
- Body: the body after the equals sign builds the result from the input.
- Reuse: the same definition can be called with different inputs.
In this example, double multiplies its input by 2, quadruple calls double on its input and then calls double again on that result, and main prints quadruple 3, which is 12.
Note
Haskell writes the inputs after the name with spaces between them.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
For the definition double x = x * 2, what does print (double 7) print?