Skip to content
Higher-Order Functions
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions

Functions are first-class values. They get passed around constantly.

-- Apply a function twice
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)

applyTwice (+ 3) 5    -- 11
applyTwice (* 2) 5    -- 20

The (+ 3) is an operator section — partially-applied operator. (/2), (>0), ("hi "++) all work.

Anonymous functions (lambdas) use \args -> body:

map (\x -> x * x) [1, 2, 3]   -- [1, 4, 9]
filter (\x -> x > 0) xs

Function composition with .:

showSquared :: Int -> String
showSquared = show . square    -- (show . square) x = show (square x)

$ is low-precedence application — lets you avoid parens:

putStrLn (show (1 + 2))
putStrLn $ show $ 1 + 2     -- same

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…