Haskell报错‘Variable not in scope: [Integer] -> t’求解决
Fixing the Scope Error in Your Haskell Ascending List Checker
Hey there! That "Variable not in scope" error is popping up because your code has a few syntax and structural issues throwing the compiler off. Let's break this down and fix it step by step.
What's Going Wrong
Your code has three key problems:
- Function Order Issue: Haskell requires functions to be defined before they’re used. You call
trackerinsideascending, buttrackeris defined afterascending—so the compiler can’t find it when parsingascending. - Broken Guard Syntax: When using guards (
|), you don’t need to wrap the condition inif—the guard itself acts as the conditional check. Your current guard syntax is invalid. - Missing Recursion Logic: Your
trackeronly checks the first pair of elements and stops. It doesn’t keep recursing through the rest of the list to validate the full sequence.
Fixed Code
The cleanest fix is to nest tracker inside ascending using a where clause—this solves the scope issue and keeps related logic neatly grouped:
ascending :: Ord t => [t] -> Bool ascending [] = True ascending (x:xs) = tracker xs x where tracker :: Ord t => [t] -> t -> Bool tracker [] _ = True tracker (current:rest) prev | prev <= current = tracker rest current -- Keep checking the remaining list | otherwise = False -- Fail immediately if out of order
How This Works
- Empty List Handling: An empty list is trivially ascending, so we return
Trueright away. - Single Element List: When you pass a list like
[5],xsis empty, sotracker [] 5returnsTrue—which is correct. - Recursive Validation: The
trackerfunction carries the previous element through each check. If the current element is greater than or equal to the previous one, it continues checking the rest of the list. If any pair is out of order, it returnsFalseimmediately.
Test It Out
Try these cases to confirm the code works as expected:
ascending [1,2,3,4] -- Returns True ascending [1,3,2,4] -- Returns False ascending [] -- Returns True ascending [10] -- Returns True
内容的提问来源于stack exchange,提问作者TCripe4
相关产品推荐
相关产品推荐

