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

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 tracker inside ascending, but tracker is defined after ascending—so the compiler can’t find it when parsing ascending.
  • Broken Guard Syntax: When using guards (|), you don’t need to wrap the condition in if—the guard itself acts as the conditional check. Your current guard syntax is invalid.
  • Missing Recursion Logic: Your tracker only 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 True right away.
  • Single Element List: When you pass a list like [5], xs is empty, so tracker [] 5 returns True—which is correct.
  • Recursive Validation: The tracker function 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 returns False immediately.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 12:47:41