【问题标题】:list of lists in Haskell - How can I seperate the first element of every list without mapHaskell中的列表列表-如何在没有地图的情况下分隔每个列表的第一个元素
【发布时间】:2017-10-07 18:31:06
【问题描述】:

例如: 我在 Haskell 中的列表是:

[[1,2,3], [7,6,8], [0,3,4]]

我需要列表中每个列表的所有第一个元素。

如何在没有“地图”的情况下获得输出 [1,7,4]? 我需要一个模式匹配的解决方案,而不是这个: 列表 x = 地图头 x

【问题讨论】:

  • 提示:您可以嵌套模式。如果您有配对列表,可以使用f ((a,b):xs) = ...。对于列表列表,使用类似的模式(您可以使用: 两次)。记得抓住所有可能的情况。

标签: list haskell design-patterns pattern-matching matching


【解决方案1】:

查看maphead 函数的定义。然后只需复制实现,将两个功能合二为一。为方便起见,您只需复制map,替换函数,将map 传递给head,然后使用您自己的head。您可以使用case <expr> of ... 表达式不将自己的头部实现为单独的函数。完成所有这些工作后,您可能可以重构您的函数以使其更优雅。

【讨论】:

  • 谢谢!我会试试看! ^^
【解决方案2】:
firsts [] = []
firsts [(x:xs)] = [x]
firsts ((x:xs):xss) = x: firsts xss


> firsts [[1,2,3], [7,6,8], [0,3,4]]
[1,7,0]

【讨论】:

  • 有没有办法使用模式为内部列表添加一些空列表验证?我没能做到。
  • 它应该会失败,因为没有第一个元素。如果您想忽略空子列表,您可以为该 firsts [[]] = [] 添加规定
【解决方案3】:

我是 Haskell 的新手,但这是我在这里设法创建的。

我使用了列表理解和模式匹配。

--Type definition. Not mandatory but recommended.
firstItemOfEveryList :: [[a]] -> [a]
--First pattern. If the list is empty return a empty list.
firstItemOfEveryList [] = [] 
--Catch all pattern. Receive a list of lists (xxs). For every inner list (xs <- xxs) call the head method (head xs), but only when the inner list is not null or empty (not(null xs).
firstItemOfEveryList xxs = [head xs | xs <- xxs, not(null xs)]

空列表模式有点不必要,因为它只是给出与最后一个捕获相同的结果。希望对您有所帮助。

【讨论】:

  • 非常好!!!我是 Haskell 的菜鸟。你能解释一下“/= []”这部分是帮助功能吗?我可以在新函数中写此评论吗?
  • 这只是一个验证。我正在检查当前的内部列表是否不为空,因为如果列表为空,head 会抛出错误。如果你想把这个验证放在一个单独的函数中,你可以这样做:firstItemOfEveryList xxs = [head xs | xs &lt;- xxs, validateList xs] where validateList x = x /= [],或者在全局范围内声明另一个函数
  • 您不需要任何那些约束,只需要Eq a。如果你用not (null xs) 替换xs /= [],你也不需要那个。
  • 感谢 Alexey 的提示。刚刚确定了答案。在处理 Haskell 类型类时,我仍然有点迷茫。
【解决方案4】:

使用嵌套模式匹配的另一个答案:

firsts :: [[a]] -> [a]
firsts      []      = []
firsts   ([]:xss)   = error "sublist is empty"
firsts ((x:xs):xss) = x:firsts xss

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多