Concatenation of lists in Haskell eliminating repetitions

Asked

Viewed 1,119 times

3

Hello, it’s been a few hours that I’m trying to make a function in Haskell that gives two lists and returns a new list

Where this new list is the union of the other two lists but without repetitions , that is, a list [1,2,3][3,2,1] should return [1,2,3] or a list [10,20,30][90,80,30] should return [10,20,30,90,80] (see that 30 is on both lists, so it should not be on the list)

What I have is this :

uniaoS :: [Int] -> [Int] -> [Int]

uniaoS [] [] =[]

uniaoS [] (x:xs) =(x:xs)

uniaoS (x:xs) [] =(x:xs)

uniaoS(a:as)(x:xs) 

| (a == x) = uniaoS as xs 

| otherwise = a:as ++ x:xs

In this case it is returning the list minus the repetitions , ie [1,2,3] [1,2,4] returns [3,4], but I would also like you to return the repeated elements [1,2,3,4]

1 answer

3

Let us begin by trying to understand why its function uniaoS returns [3, 4] and not [1, 2, 3, 4]

Using your example, the input data is the lists [1,2,3] and [1,2,4] and the definition of the function is

uniaoS(a:as)(x:xs) 
    | (a == x) = uniaoS as xs 
    | otherwise = a:as ++ x:xs

At the entrance of the function, a = 1 and x = 1, we’ll soon be on the case (a == x) = uniaoS as xs. What happens here is that you simply dismiss the a and the x and recursively evaluates the two lists until finding a case where a is different from x.

Knowing this, I leave a suggestion (not the complete answer) for resolution. Usually a good way to solve a problem is to divide it into parts. In this case your problem can be divided into:

  1. Concatenate two lists
  2. Remove the duplicate elements

Assuming you have a function that removes duplicates from a list and this function has the following signature f :: [Int] -> [Int], then the only thing you need is to concatenate the two lists before applying f. In Haskell this can be done as follows:

concatenarListas:: [Int] -> [Int] -> [Int]
concatenarListas xs ys = f (xs ++ ys)

The only thing missing is the definition of function f.

If you cannot reach a definition for f please let me know and update the answer.

  • 2

    Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.