user defined higher order functions in haskell
i went though several Haskell 开发者_Python百科learning examples but i could not figure out how to write user defined higher order functions in Haskell
if we are taking a parameter as a function how the type of the function id defined?
Let's use the function map
as a simple example. map
takes a function and a list and applies the function to all elements of the list. If you write the signature of map
, it runs like this:
First, you need a function. Any function is OK, so the type of the first argument is a -> b
. Then, you need a list of input values. Since the type of the list's elements must fit to the function's input, the type of the list is [a]
. For the output: What is the result of a function a -> b
when applied to a value of type a
? Right, it is b
. So the result type is [b]
. Assembled together, the type of our function runs like this:
map :: (a -> b) -> [a] -> [b]
And is defined like this:
map f [] = []
map f (x:xs) = f x : map f xs
Does this help you to understand the concept of high order functions?
Don't concern yourself with types just yet. Ask the compiler, it will tell you the types. With some practice you will be able to see the types almost as well as the compiler [grin].
Here we define two very simple higher-order functions, twice
and compose
. The first one takes a function and an argument, and applies one to the other, twice. The second one takes two functions and an argument and applies both functions to it in chain.
$ ghci
GHCi, version 6.12.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> let twice f x = f (f x)
Prelude> :t twice
twice :: (t -> t) -> t -> t
Prelude> let compose f g x = f (g x)
Prelude> :t compose
compose :: (t1 -> t2) -> (t -> t1) -> t -> t2
Prelude>
You can see that twice
gets two arguments, of type (t->t)
an of type t
, and returns a resulkt of type t
. t
is any type (but the same in all 4 occurrences).
You can try to use these higher-order functions on some regular functions.
Prelude> let times3 x = x * 3
Prelude> let times5 x = x * 5
Prelude> twice times3 2
18
Prelude> twice times5 2
50
Prelude> compose times3 times5 2
30
Prelude>
Ans some funky advanced stuff:
Prelude> (twice twice) times3 2
162
Prelude> twice (twice times3) 2
162
Prelude>
Do you understand what's going on in the last two examples?
精彩评论