0

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?

1
  • In general, you should use (h:t) instead of [h]++t (so here (head x):(leng (tail x))). (:) is Haskell's cons function, adding a single item to the front of a list. Commented May 8, 2013 at 16:01

2 Answers 2

6
-- 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 
Sign up to request clarification or add additional context in comments.

Comments

4

Add:

leng [] = [] 

before the current leng x.

But you could also do:

leng x = filter (<=500) x 

and even

leng = filter (<=500) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.