我正在尝试为我的输入列表列表创建一个过滤器,以删除最后一个元素不是列表列表最后一个列表元素的列表
我对haskell相当新,所以这可能只是一些愚蠢的新秀错误
FilterBoi xs = filter (\x -> elem (x) y) xs
Where x = last (x:xs)
y = last xs
返回错误
Occurs check: cannot construct the infinite type:
a ~ t0 a
Expected type: [t0 a]
Actual type: [a]
In the first argument of `last' , namely `xs'
In the expression: last xs
In an equation for `y' : y = last xs
Relevant bindings include
y :: t0 a (bound at filter.hs:3:22)
xs :: [a] (bound at filter.hs:1:11)
FilterBoi :: [a] -> [a] (bound at filter.hs:1:1)
Failed, modules loaded: none.
请注意我是在手机上输入的,所以问题不在于我输入的方式,而在于我输入了什么
答案 0 :(得分:1)
您可能正在寻找类似
的内容filterBoi :: [[a]] -> [[a]]
filterBoi xs = filter (\x -> elem (last x) y) xs
where y = last xs
请注意last
是危险的,如果应用于空列表,则会导致程序崩溃。因此,如果xs
为空,或x
内的任何列表xs
为空,则可能会崩溃。
(顺便说一句,如果xs
为空,y
将永远不会被评估,因此不会出现崩溃。但是,这并不容易发现,使代码更难阅读。)
假设我们要丢弃空x
,则替代方案是。
filterBoi :: [[a]] -> [[a]]
filterBoi [] = [] -- not needed, but clarifies the intent
filterBoi xs = filter (\x -> not (empty x) && elem (last x) y) xs
where y = last xs