【问题标题】:How to read from a file using Haskell? [duplicate]如何使用 Haskell 从文件中读取? [复制]
【发布时间】:2019-09-11 05:29:34
【问题描述】:

我正在尝试从文件中读取。我想将文件中的每一行拆分为自己的字符串。我正在考虑使用 lines 命令来制作所有行的字符串列表。然后我计划使用 words 命令将每一行溢出到单词列表中。但是,我对函数式编程/Haskell 非常陌生,而且我并不完全理解语法。那么,首先,如何从文件中读取每一行并存储它?

我尝试了以下代码,但无法编译。

main :: IO ()
main = do
  contents <- readFile "input.txt" 
  contents1 = lines contents

【问题讨论】:

    标签: file haskell functional-programming system.io.file


    【解决方案1】:

    它无法编译的原因有两个。首先,let 不存在,引用 GHC:

    Perhaps you need a 'let' in a 'do' block?
        e.g. 'let x = 5' instead of 'x = 5'
    

    另一个是:

    The last statement in a 'do' block must be an expression
      let contents1 = lines contents
    

    修复后编译并运行:

    main :: IO ()
    main = do
      contents <- readFile "input.txt" 
      let contents1 = lines contents
      print contents1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 2017-11-14
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多