Haskell报错“No instance for (Num a) arising from a use of ‘+’”求助
Hey there! Let's break down why your code is throwing that error and get it working properly.
First, let's unpack the error message: No instance for (Num a) arising from a use of ‘+’. Here's the root of the problem:
Your type signature final' :: [a] -> a tells Haskell this function should work with any type of list—whether it's numbers, strings, custom data types, you name it. But inside your foldl lambda, you're using - and + operations, which only work with types that belong to the Num type class (like integers, floats, and other numeric types). Haskell can't apply numeric operations to a random, unconstrained type a, so it throws this error to flag the mismatch.
Also, let's simplify your fold logic: accum - accum + x is just a roundabout way of writing x (since any number minus itself is 0, plus x leaves you with x). Your current fold is effectively just grabbing the last element of the list, but you're forcing it to use numeric operations to do so.
Fix Option 1: Keep Numeric Behavior (Empty List Returns 0)
If you want to retain the original behavior where an empty list returns 0, just add the Num constraint to your type signature—this tells Haskell that a must be a numeric type:
final' :: Num a => [a] -> a final' lst = foldl (\accum x -> accum - accum + x) 0 lst
Or even cleaner, since we know the logic reduces to keeping the last x:
final' :: Num a => [a] -> a final' lst = foldl (\_ x -> x) 0 lst
Fix Option 2: Make It Generic (Works for Any Type)
If you want this function to work with any type of list (not just numbers), rewrite the fold to avoid numeric operations entirely. Note that an empty list will throw an error here (since there's no "last element" to return)—this matches the behavior of Haskell's built-in last function:
final' :: [a] -> a final' lst = foldl (\_ x -> x) (error "final': empty list") lst
Or even more idiomatically, just use the built-in last function directly:
final' :: [a] -> a final' = last
Either way, the core issue was that your type signature was too broad for the operations you were using. Adding the proper constraint or simplifying the logic fixes the error.
内容的提问来源于stack exchange,提问作者hdizzle

