Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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, let's assume that the input parameter is an Integer and the list is an Integer list. Here is the code I have, Please tell me what's wrong with the following code

areTheySame :: Int -> Int-> [Int]  areTheySame x y | x == y = []                 | otherwise = [y]  removeItem :: Int -> [Int] -> [Int]  removeItem x (y:ys) = areTheySame x y : removeItem x ys 
like image 237
BM. Avatar asked Jan 19 '10 22:01

BM.


People also ask

How do I remove an element from a list in Haskell?

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 ++ .


1 Answers

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.

like image 113
Chuck Avatar answered Feb 05 '23 07:02

Chuck