Haskell传递列表作为函数参数失败,求排查解决方法
bsearch Call Hey there! Let's break down why you're seeing that type mismatch error and how to fix it.
The Root Cause
Haskell uses whitespace for function application, not parentheses and commas like languages like Java or C. When you wrote:
bsearch([1,2,3,4], 3 , 0::Int , 4::Int)
You weren't passing four separate arguments to bsearch—you were passing a single 4-tuple (([Integer], Integer, Int, Int)) as the first argument. But bsearch expects its first argument to be a list [a], hence the error: "Couldn't match expected type [a]' with actual type ([Integer], Integer, Int, Int)'".
The Fix
Rewrite the call using spaces to separate each argument, no parentheses or commas needed:
bsearch [1,2,3,4] 3 0 4
If you want to explicitly specify the integer types for the bounds (though GHC can usually infer this), you can add type annotations to individual arguments:
bsearch [1,2,3,4] 3 (0::Int) (4::Int)
A Quick Note on Haskell Function Application
In Haskell, every function takes exactly one argument. Functions that seem to take multiple arguments are actually curried: bsearch is a function that takes a list [a] and returns another function, which takes an a, then another function that takes an Int, then another that takes an Int, finally returning an Int. Whitespace lets us chain these applications cleanly without extra syntax.
Testing the corrected call should return 1 as expected, since 3 is not less than the middle element of your list (xs !! 2 is 3).
内容的提问来源于stack exchange,提问作者user7111260

