繁体   English   中英

Haskell List递归错误?

[英]Haskell List Recursion mistake?

嘿,我对Haskell还是陌生的。

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

import Data.List

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

我得到正确的输出,但是每个输出的结尾是

例外:Prelude.head:空列表

如何解决这个问题?

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

加:

leng [] = []

在当前leng x之前。

但是您也可以这样做:

leng x = filter (<=500) x

乃至

leng = filter (<=500)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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