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

前端 未结 7 1148
伪装坚强ぢ
伪装坚强ぢ 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:33

    For reference, you may be interested in seeing how it's done in delete from Data.List.

    You could leave areTheySame as is, but you'd then need to use concatMap in removeItem to collapse the empty lists:

    removeItem :: Int -> [Int] -> [Int]
    removeItem x xs = concatMap (areTheySame x) xs
    

    or equivalently

    removeItem :: Int -> [Int] -> [Int]
    removeItem x = concatMap (areTheySame x)
    

    Note that the types of your functions could be more general:

    areTheySame :: (Eq a) => a -> a -> [a]
    removeItem  :: (Eq a) => a -> [a] -> [a]
    

    This allows removal of items from lists of any type for which == is defined, not just Int.

提交回复
热议问题