theBean
theBean

Reputation: 133

Compare two lists and return the first element that is in both lists

  element1 :: [a] -> [a] -> [a]
  element1 [] [] = []
  element1 [] _ = []
  element1 _ [] = []

  element1 (h1:t1) (h2:t2) = if 

I'm Stuck and not sure how to proceed from here, I want to check two lists and return the first element that is in both lists

Upvotes: 1

Views: 293

Answers (2)

JosEduSol
JosEduSol

Reputation: 5426

You can define an auxiliary predicate that checks if an element is in a list (this is already implemented in Data.List). Then in your main function you do recursion over the first list. This is one way to do it.

element1 :: (Eq a) => [a] -> [a] -> [a]
element1 [] _ = []
element1 _ [] = []
element1 (h:t) xs = if   (isInList h xs)
                    then [h]
                    else element1 t xs

isInList :: (Eq a) => a -> [a] -> Bool
isInList _ [] = False
isInList e (x:xs) = if   e == x
                    then True  
                    else isInList e xs

Some outputs:

element1 [1,2,3] [8,5,9,3] = [3]
element1 [1,2,3] [1,5,9,3] = [1]
element1 [1,2,3] [3,2,1] = [1]

Upvotes: 1

effectfully
effectfully

Reputation: 12715

It's not clear, if they should be at the same position or what. Assuming yes:

f = ((head . concat) .) . zipWith (\x y -> [x | x == y])

Or, expanded:

f xs ys = head $ concat $ zipWith (\x y -> [x | x == y]) xs ys

If an index must be minimal in the first list:

f xs ys = head [x | x <- xs, x `elem` ys] 

Upvotes: 0

Related Questions