【问题标题】:Filter list of lists based on last element of lists in list of lists and last list of list of lists根据列表列表中列表的最后一个元素和列表列表的最后一个列表过滤列表列表
【发布时间】:2018-01-11 11:12:02
【问题描述】:

我正在尝试为我的输入列表创建一个过滤器,以删除最后一个元素不是列表的最后一个列表的元素的列表

我对 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.

请注意,我是在手机上输入的,所以问题不在于我输入的方式,而在于我输入的内容

【问题讨论】:

  • A where 是每个 function 子句而不是每个 lambda 表达式。
  • 啊,谢谢。关于我应该如何实现我的目标的任何建议?
  • where 不同,let x=e in e' 可以在表达式内部使用。 (但是,您在这里并不需要它。)

标签: list haskell filter


【解决方案1】:

您可能正在寻找类似的东西

filterBoi :: [[a]] -> [[a]]
filterBoi xs = filter (\x -> elem (last x) y) xs
   where y = last xs

请注意,last 是危险的,如果应用于空列表会导致程序崩溃。因此,如果xs 为空,或者xs 中的任何列表x 为空,则可能会崩溃。

(顺便说一句,如果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

【讨论】:

  • 谢谢,我会试一试。空列表应该不是问题,这对于为不同的功能准备输入更是如此
猜你喜欢
  • 2018-03-10
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 2014-11-09
  • 2022-08-24
  • 2023-02-10
  • 1970-01-01
  • 2021-05-23
相关资源
最近更新 更多