Haskell实现diff函数报错求助:参数数量不一致问题修复
diff Function Error First, let's break down the error you're encountering:
Equations for ‘diff’ have different numbers of arguments
This happens because your recursive case of diff accepts two list arguments ((h:t)(h1:t1)), but your base case only takes one (diff [] = []). Haskell requires all definitions of the same function to use the same number of parameters.
Corrected Code
Here's the fixed version of your code, with a proper base case that handles two empty lists (since the problem specifies input lists are the same length):
data MyData3 = Same | Different Int Int deriving(Show) diff :: [Int] -> [Int] -> [MyData3] diff (h:t) (h1:t1) = if h == h1 then Same : diff t t1 else Different h h1 : diff t t1 diff [] [] = []
Key Changes Explained
- Base Case Fix: The base case
diff [] [] = []correctly terminates the recursion when both input lists are empty, which aligns with the problem's requirement of same-length lists. - Type Signature: I added an explicit type signature
diff :: [Int] -> [Int] -> [MyData3]to make the function's behavior clear and catch type-related mistakes early.
Test Case Verification
Let's confirm the function works with your examples:
Testing
diff [1,2,3,0] [1,3,4,0]:diff [1,2,3,0] [1,3,4,0] -- Output: [Same, Different 2 3, Different 3 4, Same]Testing
diff [0,0,0,0,0] [0,0,1,0,2]:diff [0,0,0,0,0] [0,0,1,0,2] -- Output: [Same, Same, Different 0 1, Same, Different 0 2]
Both cases produce the exact results you expected.
内容的提问来源于stack exchange,提问作者Yaroslav

