Concatenation of haskell lists by eliminating repetitions

3

Hello, I've been trying to make a haskell function that gives two lists a few times and returns a new list

Where this new list is the union of the other two lists but without repetitions, ie a [1,2,3] [3,2,1] list 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 in both lists, so it should not be in 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 reps, ie [1,2,3] [1,2,4] returns [3,4] , but I would like it to also return the repeated elements [ 1,2 , 3,4]     

asked by anonymous 09.05.2018 / 10:33

1 answer

3

Let's start by trying to figure out why your uniaoS function returns [3, 4] and not [1, 2, 3, 4]

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

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

At function entry, a = 1 and x = 1 , then we fall into the (a == x) = uniaoS as xs case. What happens here is that you simply discard a and x and recursively evaluate the two lists until you find a case where a is different from x .

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

  • Concatenate two lists
  • Remove duplicate elements
  • Assuming you have a function that removes duplicates from a list and that 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 the f function.

    If you can not get a definition for f, let me update the answer.

        
    09.05.2018 / 14:57