D347th
D347th

Reputation: 707

Element Comparison in a List of Pairs

I am writing a program in Haskell that takes a list of pairs and returns a list of pairs with merged coordinates like:

    [(0,2), (2,5)] returns [(0,5)]

I wrote a program I thought would work but the compiler says can't match expected type (Int, Int) against inferred type [a]

    merger :: [(Int, Int)] -> [(Int, Int)]
    merger list = [[if y == u then (x,v) else (x,y) | (u,v) <- list] | (x,y) <- list]

Any help would be appreciated and thank you for reading.

Upvotes: 1

Views: 800

Answers (1)

hammar
hammar

Reputation: 139830

Since you're using two nested list comprehensions, the result is a list of lists of tuples [[(Int, Int)]], but your type signature declares that it should only be a list of tuples [(Int, Int)]. You probably need to either concat the lists before returning them, or use just one list comprehension with two generators:

merger :: [(Int, Int)] -> [(Int, Int)]
merger list = [if y == u then (x,v) else (x,y) | (u,v) <- list, (x,y) <- list]

Though, this won't give the result you were expecting. It sounds like you want something like this instead:

merger list = [(u, y) | (u, v) <- list, (x, y) <- list, v == x]

The condition at the end ensures that you only deal with pairs where the second element of the first one equals the first element of the second.

Upvotes: 2

Related Questions