【问题标题】:remove the element from list从列表中删除元素
【发布时间】:2017-03-05 14:10:15
【问题描述】:

我将不得不创建一个名为 removeList 的递归函数。有人可以帮我吗?

【问题讨论】:

    标签: haskell recursion functional-programming pattern-matching


    【解决方案1】:

    makeList 是常规函数,而不是数据构造函数,因此您无法对其进行模式匹配。您需要在Cons 和Nil 上进行模式匹配;列表由makeList 返回的事实不相关。

    removeList :: Eq a => a -> List a -> List a
    removeList _ Nil = Nil
    removeList x (Cons y ys) | x == y = ys -- Don't recurse if you only want to remove the *first* occurrence.
                             | otherwise = Cons y (removeList x ys)
    

    您可以直接使用您的List 类型;无需将结果构建为内置列表然后再次转换。

    比较在内置列表上实现的相同函数,类型构造函数[] 和数据构造函数(:) 用于前缀位置而不是中缀位置。

    removeList' :: Eq a => a -> [] a -> [] a
    removeList' _ [] = []
    removeList' x ((:) y ys) | x == y = ys
                             | otherwise = (:) y (removeList' x ys)
    

    只是为了好玩,让我们概括一下这段代码,以便它可以用作removeFirst 和removeAll 的基础:

    removeGeneric :: Eq a => (List a -> List a) -> a -> List a -> List a
    removeGeneric _ _ Nil = Nil
    removeGeneric f x (Cons y ys) | x == y = f y ys
                                  | otherwise = Cons y (removeGeneric f x ys)
    
    removeFirst = removeGeneric (\y ys -> ys)
    removeAll = removeGeneric removeAll
    

    removeGeneric 的第一个参数是您第一次找到匹配项时在列表中调用的函数。要删除第一个匹配项,您只需调用 tail 的等效项。要删除所有次出现,请递归。

    【讨论】:

    • 如果我想删除所有出现的内容,我应该怎么做?
    • 只是出于好奇而询问。但感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 2014-12-19
    • 2013-11-25
    • 2016-05-29
    • 2016-08-01
    相关资源
    最近更新 更多