2
votes

I am trying to learn about higher order functions from this guide here http://learnyouahaskell.com/higher-order-functions. But I am sort of confused and hoped that someone can clarify some things for me.

So I am looking at this example:

applyTwice :: (a -> a) -> a -> a  
applyTwice f x = f (f x)  

Ok so applyTwice is a function that takes two arguments, a function which takes a type a and return type a, the second argument is a type a. And the function returns a type a.

And in the command line we get this result:

ghci> applyTwice (++ " HAHA") "HEY"  
"HEY HAHA HAHA" 

So the function f is (++) and its type is [a] -> [a] -> [a]. (++ " HAHA") is a partial application correct? We have only given it one parameter and so it returns [a] -> [a]. In the applyTwice defintion, I want to start with the (f x) part. So f takes "HEY" this produces "HEY HAHA" which is type a, and then I need to apply f to get "HEY HAHA HAHA"

edit: With these two examples: what is the difference between (++ " HAHA") and ("HAHA " ++)

ghci> applyTwice (++ " HAHA") "HEY"  
"HEY HAHA HAHA"  

ghci> applyTwice ("HAHA " ++) "HEY"  
"HAHA HAHA HEY" 
3
It sounds like you've got the basic gist of it. Do you have a specific question?Chad Gilbert
(++ " HAHA") is actually a section but beyond that your understanding look correct. What do you have a problem with?Lee

3 Answers

5
votes

The difference between (++ " HAHA") and ("HAHA " ++) has to do with the order in which parameters are passed in. If we explicitly use lambdas, the expressions look like this:

(++ " HAHA") == (\x -> x ++ " HAHA") -- expands to: "HEY" ++ " HAHA"
("HAHA " ++) == (\x -> "HAHA " ++ x) -- expands to: "HAHA " ++ "HEY"
3
votes

What is the difference between (++ " HAHA") and ("HAHA " ++)?

(++ " HAHA") gives " HAHA" as the second argument to the (++) function.

("HAHA " ++) gives "HAHA " as the first argument to the (++) function.

3
votes

(++ "HAHA") is the same as (\x -> x ++ "HAHA")

whereas

("HAHA" ++) equals (\x -> "HAHA" ++ x)

This is also quite obvious from your tests. This syntax is called section and makes partial application of (non-commutative) binary operators easier and more intuitive.