Valakor
Valakor

Reputation: 15

Haskell List Recursion mistake?

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?

Upvotes: 0

Views: 135

Answers (2)

Stefan Pante
Stefan Pante

Reputation: 428

-- 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

Upvotes: 6

Bryan Olivier
Bryan Olivier

Reputation: 5307

Add:

leng [] = []

before the current leng x.

But you could also do:

leng x = filter (<=500) x

and even

leng = filter (<=500)

Upvotes: 4

Related Questions