Reading — step 1 of 5
Learn
~1 min readFunctions
Functions are defined with equations — no function or def keyword:
add :: Int -> Int -> Int
add a b = a + b
Application is just whitespace — no parens needed: add 3 4 (not add(3, 4)).
Pattern-matching across multiple equations:
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)
The compiler tries equations top to bottom. First match wins.
Currying: every function takes one argument and returns a new function. add :: Int -> Int -> Int is really Int -> (Int -> Int). add 3 returns a function that adds 3 to its arg. Lets you partially apply naturally:
addThree = add 3
map addThree [1, 2, 3] -- [4, 5, 6]
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…