防止重复打印公共列表变量Haskell
Prevent repeat printing of common list variables Haskell
目前,我正在制作一个函数,可以获取两个列表中的值,比较它们,并打印任何相似的值。如果一个值在两个列表中重复,则不会打印第二次。
EXAMPLE
INPUT: commons [1,2,2,3,4] [2,3,4,5,2,6,8]
EXPECTED OUTPUT: [2,3,4]
我目前所拥有的导致两个列表中的重复值在输出中重复。所以,在上面的例子中,2 会打印两次。
这是我正在处理的当前代码:
commons :: Eq a => [a] -> [a] -> [a]
commons [] [] = []
commons x y = commons_Helper x y
commons_Helper :: Eq a => [a] -> [a] -> [a]
commons_Helper [] [] = []
commons_Helper x [] = []
commons_Helper [] y = []
commons_Helper (x:xs) y =
if elem x y then x : commons_Helper xs y
else commons_Helper xs y
我们将不胜感激任何帮助。
编辑:这必须保留为 commons :: Eq a => [a] -> [a] -> [a],我无法导入和库
您可以将 xs
列表的遍历设置为 stateful 列表,state 跟踪具有已经看到了。状态开始时是一个空列表。
可以通过向辅助函数添加第三个参数来做到这一点,目前这不是很有用。
commons_Helper :: Eq a => [a] -> [a] -> [a] -> [a]
commons_Helper [] ys st = []
commons_Helper (x:xs) ys st =
if (elem x ys && (not $ elem x st)) -- extra test here
then x : (commons_Helper xs ys (x:st))
else commons_Helper xs ys st
commons :: Eq a => [a] -> [a] -> [a]
commons xs ys = commons_Helper xs ys []
这种state-based技术在Haskell中很常见。甚至还有一个库函数:mapAccumL :: (s -> a -> (s, b)) -> s -> [a] -> (s, [b])
来支持它。
目前,我正在制作一个函数,可以获取两个列表中的值,比较它们,并打印任何相似的值。如果一个值在两个列表中重复,则不会打印第二次。
EXAMPLE
INPUT: commons [1,2,2,3,4] [2,3,4,5,2,6,8]
EXPECTED OUTPUT: [2,3,4]
我目前所拥有的导致两个列表中的重复值在输出中重复。所以,在上面的例子中,2 会打印两次。
这是我正在处理的当前代码:
commons :: Eq a => [a] -> [a] -> [a]
commons [] [] = []
commons x y = commons_Helper x y
commons_Helper :: Eq a => [a] -> [a] -> [a]
commons_Helper [] [] = []
commons_Helper x [] = []
commons_Helper [] y = []
commons_Helper (x:xs) y =
if elem x y then x : commons_Helper xs y
else commons_Helper xs y
我们将不胜感激任何帮助。
编辑:这必须保留为 commons :: Eq a => [a] -> [a] -> [a],我无法导入和库
您可以将 xs
列表的遍历设置为 stateful 列表,state 跟踪具有已经看到了。状态开始时是一个空列表。
可以通过向辅助函数添加第三个参数来做到这一点,目前这不是很有用。
commons_Helper :: Eq a => [a] -> [a] -> [a] -> [a]
commons_Helper [] ys st = []
commons_Helper (x:xs) ys st =
if (elem x ys && (not $ elem x st)) -- extra test here
then x : (commons_Helper xs ys (x:st))
else commons_Helper xs ys st
commons :: Eq a => [a] -> [a] -> [a]
commons xs ys = commons_Helper xs ys []
这种state-based技术在Haskell中很常见。甚至还有一个库函数:mapAccumL :: (s -> a -> (s, b)) -> s -> [a] -> (s, [b])
来支持它。