我编写了这个简单的函数,它采用两个文件名(字符串)并将第一个文件的内容写入第二个文件应用toUpper
到每个角色。
import Data.Char
ioFile f1 f2 = do
s <- readFile f1
sUp <- [toUpper c | c <- s]
writeFile f2 sUp
但是解释器会报错
Couldn't match expected type ‘IO String’ with actual type ‘[Char]’
In a stmt of a 'do' block: sUp <- [toUpper c | c <- s]
In the expression:
do { s <- readFile f1;
sUp <- [toUpper c | c <- s];
writeFile f2 sUp }
In an equation for ‘ioFile’:
ioFile f1 f2
= do { s <- readFile f1;
sUp <- [toUpper c | c <- s];
writeFile f2 sUp }
我该如何使用s
as a [Char]
代替IO String
?
你不能绑定像这样的“纯”值sUp <- [toUpper c | c <- s]
这边走。请注意,与接受的答案所建议的不同,这并不意味着您不能给它命名。其一,有return
将纯值提升为IO
(或者任何单子,但我们在IO
现在),所以sUp <- return [toUpper c | c <- s]
does工作。还有一个 let 语法的变体几乎可以做到这一点:let sUp = [toUpper c | c <- s]
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)