为什么我收到 "Not in scope" 异常消息?

Why I get "Not in scope" exception message?

我学Haskell。我的代码:

main = do
  args <- getArgs
  if length args < 2 then 
    putStrLn invalidCallingSignature 
  else
    dispatch fileName command commandArgs
    where (fileName : command : commandArgs) = args -- But I get an Exception: src3.hs:22:48: Not in scope: `args'

我对最后一行代码出现的异常感到困惑。为什么我得到它?

where 子句适用于整个函数,缩进会误导您。编译器看到的是:

main = do
    args <- getArgs
    if length args < 2 then 
        putStrLn invalidCallingSignature 
    else
        dispatch fileName command commandArgs
  where (fileName : command : commandArgs) = args

因此 args 不可见。你想要一个 do-notation let:

main = do
    args <- getArgs
    if length args < 2 then 
        putStrLn invalidCallingSignature 
    else do
        let (fileName : command : commandArgs) = args
        dispatch fileName command commandArgs