如何用Maybe从列表获取元素?Haskell函数模式匹配报错求助
hello Function Hey there! Let's fix that parse error step by step — it's a common syntax gotcha when you're new to Haskell's function definition style.
The Root Cause of the Parse Error
Haskell uses prefix-style function application by default: the function name must come before all its arguments. Your current code tries to use hello like an infix operator (sandwiched between arguments), which is why the parser throws an error on (x:xs) hello i.
Corrected Code
First, note that Maybe is already defined in Haskell's standard library, so you don't need to redefine it. Here's the fixed version of your function:
hello :: [a] -> Integer -> Maybe a hello [] _ = Nothing -- Empty list: return Nothing no matter the index hello (x:xs) 0 = Just x -- Index 0: return the first element hello (x:xs) i = hello xs (i - 1) -- Recurse on the tail, decrement the index
Let's Break Down the Fixes
- We moved
helloto the start of each function clause (e.g.,hello [] _instead of[] hello _). This follows Haskell's required syntax for prefix function definitions. - The empty list clause is placed first: this ensures we handle empty lists immediately, before trying to pattern-match on a non-empty list.
- The recursive step correctly passes the tail of the list (
xs) and the decremented index (i-1) to the next call ofhello.
Verifying the Expected Results
Let's test the cases you mentioned:
hello [1..10] 4returnsJust 5: since Haskell uses 0-based indexing, index 4 corresponds to the 5th element in the list.hello [1..10] 10returnsNothing: the list[1..10]has 10 elements, with indices from 0 to 9. Index 10 is out of bounds, so we returnNothing.
Quick Tip for New Haskell Developers
Haskell's pattern matching works top-to-bottom, so always order your function clauses from the most general cases (like empty lists) to more specific ones (like exact index matches) to avoid unreachable code.
内容的提问来源于stack exchange,提问作者gewissen

