How to compare 2 lists and return another list with equal elements? - Haskell

Asked

Viewed 88 times

0

My code is this

comparar :: [Int] -> [Int] -> [Int]
comparar [] [] = []
comparar (a:as) (b:bs) = [x | x <- as, x == b] ++ [x | x <- bs, x == a]

What’s wrong with the code above?

Situation: I want to learn how to find equal elements in 2 lists or more, to make the MDC (Maximum Common Divisor)

Example: I want to do the MDC of the list [150,200,300]

create a function that generates the list of splitters of each elements

divisors 150 = [1,2,3,5,6,10,15,25,30,50,75,150]

divisors 200 = [1,2,4,5,8,10,20,25,40,50,100,200]

divisors 300 = [1,2,3,4,5,6,10,12,15,20,25,30,50,60,75,100,150,300]

compare "splitters 150" with "splitters 200" with function compare (that is, the code up there) and the result is [1,2,5,10,25,50] and then I compare this to the new list with "divisors 300" that will give the same thing, use the function Greater to find the largest number and that will be the MDC.

1 answer

1

From what I understand you need a function that removes the elements in common from two lists? Proposed function:

comparar :: [Int] -> [Int] -> [Int]
comparar [] l  = []
comparar l  [] = []
comparar (h:t) l2
    | elem h l2 = h:comparar t l2
    | otherwise = comparar t l2


using lists in comprehension becomes simpler:

comparar :: [Int] -> [Int] -> [Int]
comparar l l2 = [ x | x <- l , elem x l2]

Browser other questions tagged

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