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

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

    The : operator doesn't do what you think it does:

    (:) :: a -> [a] -> [a]
    

    It takes an item of type a and adds it to the beginning of a list of type a. You're using it to join two lists of type a. For that, you need to use ++:

    (++) :: [a] -> [a] -> [a]
    

    Also, if you make a recursive function, it needs an ending condition. So try this:

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

    That way, when you get to the end of the list, the function will stop recursing.

提交回复
热议问题