實作
oddPairs :: [Int] -> [Int] -> [(Int, Int)]回傳對串列的函式,但前提是引數串列的各個元素的總和為奇數。例如:
oddPairs [1,2,3] [2,2,2] == [(1,2),(3,2)]
oddPairs [1,3,5] [2,4,6] == zip [1,3,5] [2,4,6]
oddPairs [1,2,3] [1,2,3] == []
到目前為止,我已經嘗試過
oddPairs (x:xs) (y:ys) | (x y) `mod` 2 == 0 = []
| (x y) `mod` 2 /= 0 = [(x, y)] oddPairs (xs) (ys)
在第一個示例中,它只回傳[(1,2)],在第二個示例中,它回傳正確的值但有Non-exhaustive patterns錯誤。
uj5u.com熱心網友回復:
如果這兩個專案是偶數,您不應該只回傳一個空串列,而是繼續遞回直到至少一個串列用完,所以:
oddPairs :: Integral a => [a] -> [a] -> [(a, a)]
oddPairs [] _ = []
oddPairs _ [] = []
oddPairs (x:xs) (y:ys)
-- keep searching for new items ↓
| (x y) `mod` 2 == 0 = oddPairs xs ys
| otherwise = (x, y) : oddPairs xs ys
uj5u.com熱心網友回復:
看待問題的另一種方式是,您只需要具有奇數和的對。這是可能導致以下重點的輕微差異。
使用該zip函式將每個串列組合成對。然后用于filter查找具有奇數和的那些。
oddPairs :: Integral a => [a] -> [a] -> [(a, a)]
oddPairs f s = filter oddPair (zip f s)
where oddPair (l, r) = not $ even (l r)
uj5u.com熱心網友回復:
使用串列理解非常簡單:
oddPairs :: [Int] -> [Int] -> [(Int, Int)]
oddPairs ms ns = [(m, n) | (m, n) <- zip ms ns, odd (m n)]
的確:
> oddPairs [1, 2, 3] [2, 2, 2] == [(1, 2),(3, 2)]
True
> oddPairs [1, 3, 5] [2, 4, 6] == zip [1, 3, 5] [2, 4, 6]
True
> oddPairs [1, 2, 3] [1, 2, 3] == []
True
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/334076.html
上一篇:簡單關系遞回
下一篇:如何檢測遞回函式的最后一次呼叫?
