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 (fx)
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"
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"
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.
(++ "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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.