简体   繁体   English

尝试编写 Haskell 函数以获取字符串参数并附加到文件

[英]Trying to write Haskell function to take string parameter and append to file

I am trying to write a function that takes a string as input and appends it to a file.我正在尝试编写一个将字符串作为输入并将其附加到文件的函数。 the file is the same file every time.该文件每次都是同一个文件。 the function compiles correctly but gives the error该函数编译正确,但给出了错误

"No instance for (Show (String -> IO ())) arising from a use of `print'". “没有因使用‘打印’而产生的 (Show (String -> IO ())) 实例”。

The code is:代码是:

appendText :: String -> IO ()

appendText [] = return ()

appendText x = appendFile "testfile.txt" x 

I understand the problem is something to do with types and the Show type but I'm having trouble understanding the problem and how to correct it.我知道问题与类型和 Show 类型有关,但我无法理解问题以及如何纠正它。 Any help would be great.任何帮助都会很棒。

Edit: I am calling it as a function, eg appendFile "random text"编辑:我将其称为函数,例如 appendFile“随机文本”

Did you attempt to write something like appendText or print appendText in GHCi?您是否尝试在 GHCi 中编写类似appendTextprint appendText的内容? If so, it's attempting to Show the function, which is a type error since function types don't have a Show instance.如果是这样,它正在尝试Show函数,这是一个类型错误,因为函数类型没有Show实例。 You need to invoke it with an argument, being the particular String that you want to append to testfile.txt :您需要使用参数调用它,即您要附加到testfile.txt的特定String

appendText "test text"

The type of this is IO () , so it's an action that can be executed, and after running it you ought to see the text appear in the file. this 的类型是IO () ,所以它是一个可以执行的动作,运行它后你应该看到文本出现在文件中。

Your function can also be written more simply as:您的函数也可以更简单地编写为:

appendText x = appendFile "testfile.txt" x

Or in point-free form:或以无点形式:

appendText = appendFile "testfile.txt"

So to be clear, removing the second line allowed the function to work:所以要清楚,删除第二行允许该函数工作:

appendText :: String -> IO () appendText :: 字符串 -> IO ()

appendText = appendFile "testfile.txt" appendText = appendFile "testfile.txt"

I'm not sure why this fixed the problem, that line was there for error handling purposes but apparently wasn't needed.我不确定为什么这解决了这个问题,那条线是为了错误处理而存在的,但显然不需要。 It works though, thanks for the help.不过还是可以的,谢谢帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM