【问题标题】:Why am i getting a parse error and how can i solve this error in haskell?为什么我会收到解析错误,如何在 haskell 中解决此错误?
【发布时间】:2020-04-17 01:31:37
【问题描述】:

我是 Haskell 的新手,在阅读真实世界的 Haskell 时遇到了一个问题:

Q) 使用前面第 71 页“简单命令行框架”一节中的命令框架,编写一个程序,打印其输入的每一行的第一个单词。

命令框架是:

-- file: ch04/InteractWith.hs
-- Save this in a source file, e.g., Interact.hs

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

我的解决方法是:

-- file: ch04/InteractWith.hs
-- Save this in a source file, e.g., Interact.hs

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 = concat (map (++"\n") (map head (map words (lines input))))

按照说明,每当我尝试使用 ghc --make filename 编译此程序时,都会出现解析错误,即

error: parse error on input ‘args’
   |
36 |       args <- getArgs
   |       ^^^^

【问题讨论】:

    标签: haskell io haskell-stack ghci args


    【解决方案1】:

    您的缩进已关闭。

    Haskell 对空格很敏感。特别是,“块”的“内部”通常必须比该块的开头更向右缩进。在您的情况下,这意味着 do 的内部必须缩进到前一行 mainWith 的右侧。

    试试这个:

    main = mainWith myFunction
      where mainWith function = do
              args <- getArgs
              case args of
                [input,output] -> interactWith function input output
                _ -> putStrLn "error: exactly two arguments needed"
    

    【讨论】:

    • 它解决了第一个错误,但现在它给了我一个新错误。
    • 好吧,如果您有其他问题,请随时将其发布到 StackOverflow。我相信有人能回答。
    • 无法将预期类型 'String -> String' 与实际类型 '[Char]' 匹配 在 'mainWith' 的第一个参数中,即 'myFunction' 在表达式中: mainWith myFunction 在等式中对于'main': main = mainWith myFunction where mainWith function = do args
    • 对不起,我的互联网发生了一些奇怪的事情,没有发布其他评论。也为可怕的格式感到抱歉
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    相关资源
    最近更新 更多