Compare two element-by-element lists in HASKELL (RESOLVED)

1

I've been searching before opening a topic but I can not find something like what I need.

It is the case that I have to compare two lists with a certain condition, element by element, but I am incapable. The function has to return a Bool, True if they are the same and False if not.

This is what I have to do: Items that occupy an odd position in the first list should appear in Even position in the second list, but in reverse order. The elements that occupy even position in the first list must appear in odd position within the second list, and in the same order.

Given this, my code is as follows:

separarPorPosicion :: [a] -> ([a],[a])
separarPorPosicion [] = ([],[])
separarPorPosicion xs = (listaPar,listaImpar)
    where 
        listaPar = [ x | (x,y) <- zip xs [1..length xs], even y]
        listaImpar = [ x | (x,y) <- zip xs [1..length xs], odd y]

mellizas :: Eq a => [a] -> [a] -> Bool
mellizas [] [] = True
mellizas _ [] = False
mellizas [] _ = False 
mellizas xs ys = impar1 == reverse par2 && par1 == impar2
    where 
        par1 = [x | (x,y)<- separarPorPosicion xs]
        par2 = [x | (x,y)<- separarPorPosicion ys]
        impar1 = [y | (x,y)<- separarPorPosicion xs]
        impar2 = [y | (x,y)<- separarPorPosicion ys]

It gives me an error of types that I am unable to solve. Any ideas? Thanks in advance!

    
asked by Diego F. 23.10.2018 в 18:29
source

1 answer

0

It may still be easier.

We separate the problem into two:

-- comparar impares con impares
test1 :: Eq a => [a] -> [a] -> Bool
test1 (x:_:xs) (y:_:ys) = x==y && test1 xs ys
test1 [] [] = true
test1 _ _ = false

-- comparar pares con impares
test2 :: Eq a => [a] -> [a] -> Bool
test2 (x:_:xs) (_:y:ys) = x==y && test2 xs ys
test2 [] [] = true
test2 _ _ = false

And we do the combination:

mellizas :: Eq a => [a] -> [a] -> Bool
mellizas xs ys =  length xs == length ys 
               && even (length xs)
               && test1 xs (reverse ys)
               && test2 xs ys

Here you check that the two lists have the same even length. By the construction of the functions test1 and test2 we can realize that these functions always return false if the lists are of different length or if they have odd length, so we can skip this check to make it even simpler the mellizas function:

mellizas :: Eq a => [a] -> [a] -> Bool
mellizas xs ys = test1 xs (reverse ys) && test2 xs ys
    
answered by 24.10.2018 в 03:11