Haskell List Recursion mistake?

Tag: list , haskell , recursion Author: os421 Date: 2013-04-21

Hey I am pretty new to Haskell.

So I want to eliminate all integers which are greater than 500 in a list.

import Data.List

leng x = if(head x > 500) then leng(tail x) else [head x]++leng(tail x)

I get the right output but at the end of each output is

Exception: Prelude.head: empty list

how to fix that problem?

Best Answer

-- You need this to stop the recursion, otherwise it would try to split the list 
-- when   there are no elements left.
    leng [] = []

You could consider this as the stop condition for your method.

you could also rewrite your method as follow:

leng [] =[]
leng (x:xs) | x > 500 = leng xs
            | otherwise = x : leng xs

the first statement is often reocurring when working with lists in haskell. e.g.

last [x]    = x
-- the underscore means the value of the variable is not needed and can be ignored.
last (_:xs) = last xs

comments:

Try to compile your leng function I guess it won't work.

Other Answer1

Add:

leng [] = []

before the current leng x.

But you could also do:

leng x = filter (<=500) x

and even

leng = filter (<=500)

comments:

Thanks for your help!