James
James

Reputation: 65

How to Delete a list of tuple recursively based on parameter in Haskell

I'm trying to write a function that takes 2 parameters, the second parament takes a list of tuples. The pair of tuples gets deleted if first component is equal to the first parameter.

eg myDelete 2 [(1, 'a'), (2, 'b'), (3, ’c’)] = [(1, 'a'), (3, ’c’)]

Here is what I have tried

myDelete :: Eq a => a -> [(a, b)] -> [(a, b)]
myDelete a [] = []
myDelete a ((l, r) :xs) | a==l      = myDelete a xs
                          | otherwise = l: r:(myDelete a xs)

Upvotes: 2

Views: 78

Answers (2)

Auscyber
Auscyber

Reputation: 72

Something you could try is this.

myDelete a = filter ((/=a) . fst)

It means you would map (/=a) over the first parameter.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

The problem is the l : r : … part. You return a list of 2-tuples. l has type a, and r has type b, so you prepend the list with expressions of type a and b, but that will not work.

You should prepend the list with the 2-tuple (l, r):

myDelete :: Eq a => a -> [(a, b)] -> [(a, b)]
myDelete a [] = []
myDelete a ((l, r) :xs)
    | a == l = myDelete a xs
    | otherwise = (l, r): myDelete a xs

You can also make use of an as-pattern [Haskell report] to avoid wrapping l and r in a 2-tuple:

myDelete :: Eq a => a -> [(a, b)] -> [(a, b)]
myDelete a [] = []
myDelete a (lr@(l, _) :xs)
    | a == l = myDelete a xs
    | otherwise = lr: myDelete a xs

Upvotes: 4

Related Questions