Sunday, 5 June 2016

Haskell: Define length function using map and sum

There are many ways to do this.

Way 1
Prelude library defines const function like below.
const x _ = x

Whatever the second argument, const function always return the first argument of const function.


Example, We can implment length function like below.
Prelude> let length = sum.map(const 1)
Prelude> 
Prelude> length []
0
Prelude> length [1, 2, 3]
3
Prelude> length "Hello World"
11

Way 2
Following statement works for list of integers.

sum ( map (+1) list) - sum ( map (+0) list)
Prelude> let list = [2, 3, 4, 5]
Prelude> 
Prelude> sum ( map (+1) list) - sum ( map (+0) list)
4


Previous                                                 Next                                                 Home

No comments:

Post a Comment