0

嘿,我对 Haskell 很陌生。

所以我想消除列表中所有大于 500 的整数。

import Data.List

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

我得到了正确的输出,但在每个输出的末尾是

例外:Prelude.head:空列表

如何解决这个问题?

4

2 回答 2

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

您可以将此视为您的方法的停止条件。

你也可以重写你的方法如下:

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

在使用 haskell 中的列表时,第一个语句经常重复出现。例如

last [x]    = x
-- the underscore means the value of the variable is not needed and can be ignored.
last (_:xs) = last xs
于 2013-05-07T22:42:43.060 回答
4

添加:

leng [] = []

当前leng x.

但你也可以这样做:

leng x = filter (<=500) x

乃至

leng = filter (<=500)
于 2013-05-07T22:42:12.910 回答