List Haskell列表递归错误?
嘿,我是哈斯克尔的新手 所以我想消除列表中大于500的所有整数List Haskell列表递归错误?,list,haskell,recursion,List,Haskell,Recursion,嘿,我是哈斯克尔的新手 所以我想消除列表中大于500的所有整数 import Data.List leng x = if(head x > 500) then leng(tail x) else [head x]++leng(tail x) 我得到了正确的输出,但在每个输出结束时 例外:前奏曲。标题:空列表 如何解决该问题?添加: leng [] = [] 在当前长度x之前 但你也可以这样做: leng x = filter (<=500) x leng x=过滤器( 您可以
import Data.List
leng x = if(head x > 500) then leng(tail x) else [head x]++leng(tail x)
我得到了正确的输出,但在每个输出结束时
例外:前奏曲。标题:空列表
如何解决该问题?添加:
leng [] = []
在当前长度x
之前
但你也可以这样做:
leng x = filter (<=500) x
leng x=过滤器(
您可以将此视为方法的停止条件
您还可以按如下方式重写您的方法:
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
通常,您应该使用(h:t)
而不是[h]++t
(因此这里(head x):(leng(tail x))
。(:)是Haskell的cons函数,在列表的前面添加一个项目。
leng [] =[]
leng (x:xs) | x > 500 = leng xs
| otherwise = x : leng xs
last [x] = x
-- the underscore means the value of the variable is not needed and can be ignored.
last (_:xs) = last xs