【问题标题】:Why am I getting parse error on myFunction为什么我在 myFunction 上收到解析错误
【发布时间】:2016-10-29 15:02:37
【问题描述】:

在以下代码中,我在输入“myFunction”时遇到解析错误:

import System.Environment (getArgs)
interactWith function inputFile outputFile = do  
    input <- readFile inputFile writeFile outputFile (function input)
main = mainWith myFunction  
 where mainWith function = do         
        args <- getArgs          
        case args of            
            [input,output] -> interactWith function input output         
            _ -> putStrLn "error: exactly two arguments needed"
        -- replace "id" with the name of our function below       
        myFunction = id 

【问题讨论】:

  • 一旦你用myFunction 修复了你的错误,你会在interactWith 中遇到一个错误,因为你不能用绑定结束一个do 块。我建议尝试更频繁地编译您的代码。
  • @ReinHenrichs 我也注意到了这一点,并在我的答案中包含了假定的修复。

标签: haskell functional-programming parse-error


【解决方案1】:

myFunction = id 需要与where 子句中定义的其他事物对齐。

main = mainWith myFunction  
 where mainWith function = do         
     ^  args <- getArgs          
     |  case args of            
     |      [input,output] -> interactWith function input output         
     |      _ -> putStrLn "error: exactly two arguments needed"
     | -- replace "id" with the name of our function below       
     | myFunction = id 
     | ^
     | |
     | here
     |
     not here

同样的代码,为了更清楚,缩进更多:

import System.Environment (getArgs)
interactWith function inputFile outputFile = do  
    input <- readFile inputFile 
    -- I assume a line break belongs here 
    writeFile outputFile (function input)
main = mainWith myFunction  
    where mainWith function = do         
              args <- getArgs          
              case args of            
                  [input,output] -> interactWith function input output         
                  _ -> putStrLn "error: exactly two arguments needed"
          -- replace "id" with the name of our function below       
          myFunction = id 

【讨论】:

  • 检查我更新的代码,按照你说的做了,仍然出现解析错误。
  • @AliToto 现在它与args 对齐。您可能希望使用多个空格进行缩进。
  • myFunction 不是do 块的一部分,这就是您所说的将其与args 对齐。
【解决方案2】:

在 haskell 中这样做是不好的做法:

where a = x
  b = y

这可能会导致错误,因为它的排列不一样,所以请在 where 后面加上一个 CRNL:

where
  a = x
  b = y

【讨论】:

    猜你喜欢
    • 2013-06-04
    • 2020-06-12
    • 2016-11-15
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多