Romas Augustinavičius
Romas Augustinavičius

Reputation: 443

Haskell basic function definition

I'am learning haskell and I don't realy understand function definitions, for example:

module TestModule where

iter :: Int -> (a -> a) -> (a -> a)

iter n f 
  | n>0         = f . iter (n-1) f
  | otherwise   = id

iter_2 n f = foldr (.) id (replicate n f)

What I suppose to give this function? I have loaded this function via console and don't really understand how to use it.

My question how to use this function via console. Like "iter 5 ???"

Upvotes: 0

Views: 150

Answers (2)

karakfa
karakfa

Reputation: 67497

read the type of the function as

iter :: Int -> (a -> a) -> a -> a
        ^^^    ^^^^^^^^    ^    ^
        arg      arg      arg  result

meaning if you provide an Int, a (a->a) function, and an a, it will give you back another a. Here a stands for any type. For example

iter 4 (+1) 0

will be 4, that is performs (+1) on 0 four times.

Upvotes: 4

leftaroundabout
leftaroundabout

Reputation: 120711

You need to give it a function, more specifically, an endofunction (mapping any type to itself). For example,

*Main> iter 3 sqrt 256
2.0

Of course, this can also be a custom function, like

*Main> let f x = x+2
*Main> iter 3 f 7
13

or even an anonymous one defined right in the invocation:

*Main> iter 3 (\str -> "("++str++")") "..."
"(((...)))"

Upvotes: 3

Related Questions