[Haskell-beginners] Better way to write this?

Mihai Maruseac mihai.maruseac at gmail.com
Tue Mar 9 15:35:06 EST 2010


On Tue, Mar 9, 2010 at 10:26 PM, Tim Perry <perry2of5 at yahoo.com> wrote:
> I'm working my way through the 99 sample programs for haskell and I'm on #4: find the number of elements in a list.
> http://haskell.org/haskellwiki/99_questions/1_to_10
>
> I wrote the obvious recursion. Then I rewrote it using foldl
> myLength :: [a] -> Int
> myLength [] = 0
> myLength xs = foldl addOne 0 xs
>   where addOne lhs rhs = lhs + 1
>
> However, the solution given uses notation that confuses my little mind. Can someone point me to a good resource on this notation?
>
> myLength :: [a] -> Int
> myLength =  foldr (\x n -> n + 1) 0
>
>

Your example and that example are the same code, only rewritten.

Starting with your code, we change the arguments of addOne to be x and
n and ignore the case of an empty list since foldl on an empty list
returns the start value.

myLength xs = foldl addOne 0 xs
  where addOne x n = n + 1

Now, instead of using a named function, we inline addOne as a lambda expression:

myLength xs = foldl (\x n -> n + 1) 0 xs

(read the paranthesis as a function with to arguments, x and n, which
computes n + 1).

Now, there's is a style called point free style, in which we don't
give function arguments if they are implied and the code looks
prettier without them. If we do this to our myLength we will arrive
to:

myLength foldl (\x n -> n + 1) 0

which is exactly their solution. Observe that point-free notation is
useful when you have only one occurence of the argument and it is at
the end of the expression.

As for some resources, try looking here[0] or here[1]

[0]: http://learnyouahaskell.com/higher-order-functions#lambdas
[1]: http://book.realworldhaskell.org/read/functional-programming.html
(long reading)

-- 
Mihai Maruseac


More information about the Beginners mailing list