目前,我正在制作一個可以獲取兩個串列中的值、比較它們并列印任何相似值的函式。如果兩個串列中的值重復,則不會再次列印。
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
任何和所有的幫助將不勝感激。
編輯:這必須保持為公地:: Eq a => [a] -> [a] -> [a],我不能匯入和庫
uj5u.com熱心網友回復:
您可以使xs串列的遍歷成為有狀態的,狀態跟蹤已經看到的元素。狀態開始時是一個空串列。
可以通過向您的輔助函式添加第三個引數來做到這一點,這目前不是很有用。
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 []
這種基于狀態的技術在 Haskell 中很常見。甚至還有一個庫函式: mapAccumL :: (s -> a -> (s, b)) -> s -> [a] -> (s, [b])支持它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434062.html
標籤:哈斯克尔
