【问题标题】:Having problems with writeFile in Haskell IOHaskell IO 中的 writeFile 存在问题
【发布时间】:2016-03-16 13:37:54
【问题描述】:

首先我是新来的,感谢您的帮助。

问题基本上是我无法在 Haskell 中使用 writeFile 写入文件。 代码:

main = do
    putStrLn "Input file: "
    ifile <- getLine
    result <- readFile ifile >>= print . emit . compile . calc . lexer
    print result

这是我目前拥有的,我知道函数 emit 正在正确返回。 我正在使用的功能的其他信息:

    emit :: (Int, Int, [Stuff]) -> String
    compile :: C -> (Int, Int, [Stuff])

我可以用上面的代码打印结果,它返回如下:

"stuff i want"
()

我觉得() 很有趣,但我想我可以在之后将其从文件中删除。

当我尝试以下列方式使用 writeFile 时:

writeFile "file.txt" results

它给了我以下错误:

    Couldn't match type `()' with `[Char]'
    Expected type: String
      Actual type: ()
    In the second argument of `writeFile', namely `result'
    In a stmt of a 'do' block: writeFile "result.txt" result
    In the expression:
      do { putStrLn "Input file: ";
        ifile <- getLine;
        result <- readFile ifile >>= print . emit . compile . calc . lexer;
        writeFile "result.txt" result }

有人知道我该如何解决这个问题吗? 提前致谢!

【问题讨论】:

    标签: file haskell io


    【解决方案1】:

    “有趣”的() 实际上是理解这一点的关键。输出()main 的最后一行print result 发出,因为result 的类型为()

    为什么?因为它绑定了print . emit . compile . calc . lexer =&lt;&lt; readFile ifile的结果;或者,对于某些纯编译器管道f,简化为print . f =&lt;&lt; readFile ifile 的结果。其结果是print 的结果,即()print 不会返回任何有用的信息,它只是将其参数打印到标准输出作为效果)。

    你想要做的是不在print那里做任何事情,而只是绑定运行编译管道的实际结果;即类似

    result <- emit . compile . calc . lexer <$> readFile ifile
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-16
      • 2022-11-14
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多