I am currently learning Haskell, and I have run into not so much a problem but a point of confusion. I'm looking at examples from the e-book "Learn you a Haskell". (http://learnyouahaskell.com/higher-order-functions) and there is an example of a lambda function and foldl that I don't quite understand. So, in the example the code provided to re-create the reverse function is as follows:
reverse' :: [a] -> [a]
reverse' = foldl (\acc x -> x : acc) []
Which I have compiled, and run succesfully. However I don't understand why you don't need to specify where the list is coming from like so:
reverse' :: [a] -> [a]
reverse' e = foldl (\acc x -> x : acc) [] e
(Where e would be the list [a] from the user input).
Can someone explain this, or even point me to a document that explains it? Thanks :)
It's called η-reduction: in lambda calculus (and thus in Haskell) you can replace \x -> f x with simply f. Combine that with the fact that function definitions are actually syntactic sugar:
g x = f x
is sugar for
g = \x -> f x
so it's just
g = f
Applied to your example,
reverse' e = foldl (\acc x -> x : acc) [] e
⇌
reverse' = \e -> foldl (\acc x -> x : acc) [] e
⇌
reverse' = foldl (\acc x -> x : acc) []
This idea of ommitting function arguments which are merely passed on to some other function is called point-free style. It's pretty often used in Haskell and can make your code quite a bit more concise, as well as sometimes revealing more general mathematical structure. It may however also make your code somewhat cryptic (derogatory term: pointless style).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With