element1 :: [a] -> [a] -> [a]
element1 [] [] = []
element1 [] _ = []
element1 _ [] = []
element1 (h1:t1) (h2:t2) = if
我被困住了,不知道如何从这里开始,我想检查两个列表并返回两个列表中的第一个元素
答案 0 :(得分:1)
您可以定义一个辅助谓词,用于检查元素是否在列表中(这已经在Data.List中实现)。然后在主函数中,您在第一个列表上进行递归。这是一种方法。
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
一些输出:
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]
答案 1 :(得分:0)
目前尚不清楚,他们是否应该处于相同的位置或者是什么。假设是:
f = ((head . concat) .) . zipWith (\x y -> [x | x == y])
或者,扩展:
f xs ys = head $ concat $ zipWith (\x y -> [x | x == y]) xs ys
如果第一个列表中的索引必须是最小的:
f xs ys = head [x | x <- xs, x `elem` ys]