I\'m currently doing a Functional Programming course and I\'m quite amused by the concept of higher-order functions and functions as first class citizens. However, I can\'t yet
I really started to feel the power when I learned a function can be part of a data structure. Here is a "consumer monad" (technobabble: free monad over (i ->)
).
data Coro i a
= Return a
| Consume (i -> Coro i a)
So a Coro
can either instantly yield a value, or be another Coro depending on some input. For example, this is a Coro Int Int
:
Consume $ \x -> Consume $ \y -> Consume $ \z -> Return (x+y+z)
This consumes three integer inputs and returns their sum. You could also have it behave differently according to the inputs:
sumStream :: Coro Int Int
sumStream = Consume (go 0)
where
go accum 0 = Return accum
go accum n = Consume (\x -> go (accum+x) (n-1))
This consumes an Int and then consumes that many more Ints before yielding their sum. This can be thought of as a function that takes arbitrarily many arguments, constructed without any language magic, just higher order functions.
Functions in data structures are a very powerful tool that was not part of my vocabulary before I started doing Haskell.