【问题标题】:Removing a tuple that contains a null from list in haskell从haskell中的列表中删除包含null的元组
【发布时间】:2013-11-05 07:29:39
【问题描述】:

美好的一天!

所以我想写一个函数是Haskell如下

remove_nulls :: [ ([String], Int) ] -> [ ([String], Int) ] -> [ ([String], Int) ]
remove_nulls listofpair (y:ys)
| null listofpair = (y:ys)
| null (fst(head listofpair))= remove_nulls (tail listofpair) (y:ys)
| otherwise = remove_nulls (tail listofpair) (y:(head listofpair):ys)

接受可能看起来像这样的输入

remove_nulls [ ([],0) , (["abc", "dce"], 2) ] []

这个想法是,如果元组的第一个值中包含空值,它将从列表中删除元组。但是,每次我调用它时,它都会返回“函数 remove_nulls 中的非详尽模式”。

我尝试过更改基本情况,但总是得到相同的结果。任何帮助和利用都会很棒(目前只是学习 Haskell)。

【问题讨论】:

  • 如果第二个参数是[]会发生什么?
  • 请给出一些输入和预期输出的例子。您正在将 两个 元组列表作为输入。

标签: list haskell null tuples


【解决方案1】:

如果您只想删除所有第一个字段为空的对,

removeNulls xs = filter (not . null . fst) xs

会做到这一点。如果您还不熟悉(not . null . fst) 中的符号,那么它只是编写函数\pair -> not (null (fst pair)) 的一种更短的方法。更多解释请参见this SO question

您的原始函数似乎尝试在第二个输入列表的第一个元素之后插入第一个列表中的好元素,并且无法工作,因为它没有涵盖第二个列表为空的情况。

【讨论】:

  • 太棒了!谢谢!我不知道过滤器功能,但这会为我省去很多麻烦!
【解决方案2】:

remove_nulls 应该获取列表并返回一个新列表:

remove_nulls :: [ ([String], Int) ] -> [ ([String], Int) ]
remove_nulls lst = [(x,y) | (x,y) <- lst, (not.null) x]

【讨论】:

    【解决方案3】:

    因为您调用 remove_nulls 时使用一个空列表作为第二个参数,并且您只提供了当第二个参数至少有一个元素时的定义(这是第一行的(y:ys) 模式),所以不能匹配找到,导致您看到错误消息。

    我认为(但还没有尝试过)如果你去掉 y: 匹配,它应该编译(但可能还没有做你想做的事!)。所以尝试这样的事情:

    remove_nulls :: [ ([String], Int) ] -> [ ([String], Int) ] -> [ ([String], Int) ]
    remove_nulls listofpair ys
      | null listofpair = ys
      | null (fst (head listofpair))= remove_nulls (tail listofpair) ys
      | otherwise = remove_nulls (tail listofpair) (head listofpair:ys)
    

    【讨论】:

      【解决方案4】:

      你错过了添加一个额外的条件:当第二个列表为空时

      remove_nulls :: [([a], t)] -> [([a], t)] -> [([a], t)]
      remove_nulls [] ys = ys
      remove_nulls (([], _):xs) ys = remove_nulls xs ys
      remove_nulls (x:xs) [] = remove_nulls xs [x]       -- new condition
      remove_nulls (x:xs) (y:ys) = remove_nulls xs (y:x:ys)
      

      【讨论】:

        猜你喜欢
        • 2015-05-22
        • 1970-01-01
        • 2017-04-22
        • 1970-01-01
        • 2016-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多