You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell实现diff函数报错求助:参数数量不一致问题修复

Fixing the Haskell 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:

  1. 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]
    
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:31:51