Learning Haskell: How to remove an item from a List in Haskell

前端 未结 7 1147
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 19:06

Trying to learn Haskell. I am trying to write a simple function to remove a number from a list without using built-in function (delete...I think). For the sake of simplicity, le

7条回答
  •  粉色の甜心
    2021-02-01 19:35

    This is the minimal fix to make your example work:

    removeItem :: Int -> [Int] -> [Int]
    removeItem _ []     = []
    removeItem x (y:ys) = areTheySame x y ++ removeItem x ys
    

    First, you need to use ++ to concatenate lists, as the : operator used by you adds just one element to the beginning of a list (it can neither be used to add lists with one element nor to add empty lists). You first compare the head of the list (y) to the item you want to remove and correctly return the item or an empty list using areTheySame. Then you want to recursively continue using removeItem on the rest of the list (ys). The resulting list needs to be concatenated using ++.

    Second, as Chris Lutz noted, you need an ending condition when you reach the end of the list. By adding this line, Haskell knows what to do with an empty list (that is, nothing, just return an empty list).

    As Chuck said, you can simplify the code for this task by having removeItem not delegate the task of the comparison, but compare itself and throw away the element if it should be removed, otherwise keep it at the list head (using :). In any case, continue recursively with the rest of the list.

    -- nothing can be removed from an empty list
    -- ==> return empty list and stop recursion
    removeItem _ []     = []
    
    -- if the list is not empty, cut off the head in y and keep the rest in ys
    --                    if x==y, remove y and continue
    removeItem x (y:ys) | x == y    = removeItem x ys    
    --                    otherwise, add y back and continue 
                        | otherwise = y : removeItem x ys
    

提交回复
热议问题