简体   繁体   中英

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?

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

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

Add:

leng [] = []

before the current leng x .

But you could also do:

leng x = filter (<=500) x

and even

leng = filter (<=500)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM