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:
Now, we could do something like this:
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.
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 -> aA 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 valueSo,our function checks when predicate (first parameter) is true returns value (second parameter) divided by 2, otherwise - returns value (without any changes).
| (predicate value) = (value `div` 2)
| otherwise = value
Now, we could do something like this:
ghc> g (>10) 20or :
10
ghc> g (>10) 5
5
ghc> let predicate a = a `mod` 2 == 0In 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.
ghc> g predicate 12
6
ghc> g predicate 157
157
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