【问题标题】:Opening Files in Haskell using String parameters使用字符串参数在 Haskell 中打开文件
【发布时间】:2013-10-09 12:57:18
【问题描述】:

我正在学习 Haskell,但我还不是很擅长... 我读过的一些教程(Haskell's String IOLearn You a Haskell)已经解释了很多关于 IO 的事情,但我仍然无法编写我想要的函数:

TutorialCopy inputName outputName = do
                                    contents <- Str.readFile inputName  -- Opens the target File.
                                    writeFile outputName contents       -- Creates the destination File.

这里的想法是根据输入文件的位置('inputName')读取文件,并将其内容传输到输出文件('outputName')。我也试过函数类型:

TutorialCopy :: FilePath -> FilePath -> IO ()

甚至:

TutorialCopy :: String -> String -> IO ()

没有任何成功,因为 GHCi 在我声明签名时返回签名错误,或者在我不声明时返回数据构造函数错误。

感谢所有帮助,谢谢!

【问题讨论】:

  • 这里的Str 是什么?使用Str.readFile 似乎很奇怪,但随后使用普通的writeFile 而不是Str.writeFile

标签: file haskell io


【解决方案1】:

Haskell 有一些强制的命名约定。函数名必须以小写字母开头,数据类型和构造函数必须以大写字母开头。将您的函数名称更改为tutorialCopy,这应该可以解决它。

【讨论】:

  • 谢谢,它帮助了但没有解决问题...这次它产生了一个不同的错误:IOTutorial01.hs:14:94: Couldn't match type Str.ByteString'和[Char]' Expected type: String Actual type: Str.ByteString In the second argument of writeFile',即contents' In a stmt of a 'do' block: writeFile outputName contents In the expression: do { contents &lt;- Str.readFile inputName; writeFile outputName contents }
  • @Zeh 这意味着您正在尝试使用ByteString 接口而不是String 接口来读取文件。 ByteString 是一个库提供的类型,它有很多有用的应用程序,而 String 只是没有削减它,它非常适合网络 IO 之类的东西。
  • @bheklilr 问题是,我没有在我的代码中明确使用任何ByteString,这与我在问题中的那个完全一样。
  • @Zeh,首先,这是一个不同的问题。其次,如果您需要帮助,请将Str 的定义添加到您的问题中(或者,更好的是,完全创建一个最小的工作示例)。
  • @Zeh 您正在使用Str.readFile,我假设它来自ByteString 模块之一,尽管很难说,因为您的代码示例中没有该导入语句,但是内置的readFile 返回一个String
猜你喜欢
  • 2020-03-02
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多