Reputation: 167
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"
Upvotes: 2
Views: 248
Reputation: 18420
(++ "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.
Upvotes: 3
Reputation: 36385
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"
Upvotes: 4
Reputation: 83587
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.
Upvotes: 3