April 10, 2012

Haskell. First steps.

Today I gonna touch very important thing in Haskell - high-order functions and types.
Actually, I split this topic in several posts. Thereby, welcome to the first part of those series.


In Haskell functions can take functions as parameters and returns functions as values.
For example, we have a type of some function g:
g :: (Integral a) => (a -> Bool) -> a -> a
A straightforward way of reading the type signature would be "g takes function (predicate) with parameter and returns new value". Take a look at this :
g predicate value
| (predicate value) = (value `div` 2)
| otherwise = value
So,our function checks when predicate (first parameter) is true returns value (second parameter) divided by 2, otherwise - returns value (without any changes).

Now, we could do something like this:
ghc> g (>10) 20
10
ghc> g (>10) 5
5
or :
ghc> let predicate a = a `mod` 2 == 0
ghc> g predicate 12
6
ghc> g predicate 157
157
In the second example I used let binding(this construction let you bind values with names). So, predicate is a function that takes parameter and checks its remainder of the division on 2.
Therefore, in the first test (with 12 as second parameter) function g returns 6 (predicate is true for 12) and in the second test - returns 157.

Hope, these examples is clear for you.

No comments:

Post a Comment