为什么我会收到"不在范围内"的异常消息?

And*_*man 2 haskell

我学习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'
Run Code Online (Sandbox Code Playgroud)

我对最后一个代码行的异常感到困惑.为什么我明白了?

Seb*_*edl 7

where条款适用于整个函数,缩进会误导您.编译器看到的是:

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

所以args不可见.你想要一个记号let:

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

  • 这里的case语句可能更漂亮:`case args of {fileName:command:commandArgs - > dispatch fileName command commandArgs; _ - > putStrLn invalidCallingSignature},但这只是个人偏好的问题.但是,case语句意味着不需要遍历查找长度的列表. (3认同)