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

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

    The others are right that the problem is the : operator. I would say that your areTheySame function that returns a list is the wrong approach anyway, though. Rather than switch to the ++ operator, a better implementation of that function would be:

    removeItem _ []                 = []
    removeItem x (y:ys) | x == y    = removeItem x ys
                        | otherwise = y : removeItem x ys
    

    As you can see, this is a pretty simple implementation. Also, consing like this is much less taxing for your program than appending a bunch of lists together. It has other benefits as well, such as working lazily.

提交回复
热议问题