Bea*_*row 3 recursion haskell modulo
实现
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)
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,它仅返回[(1,2)],在第二个示例中,它返回正确的值,但有Non-exhaustive patterns错误。
如果两项为偶数,则不应仅返回空列表,而应继续递归,直到至少用完其中一个列表,因此:
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 ysRun Code Online (Sandbox Code Playgroud)