【发布时间】:2011-10-01 12:10:23
【问题描述】:
我想写函数并将结果放到字符串中。
我想要功能:
read' :: FilePath -> String
我用:
:t readFile
readFile :: FilePath -> IO String
我做:
read' :: IO ()
read' = do
str <- readFile "/home/shk/workspace/src/test.txt"
putStrLn str
我想问str是不是字符串?
我们知道:
:t putStrLn
putStrLn :: String -> IO ()
那为什么我不能:
read' :: String
read' = do
str <- readFile "/home/shk/workspace/lxmpp/src/test.txt"
str
我收到以下错误:
Couldn't match expected type `[t0]' with actual type `IO String'
In the return type of a call of `readFile'
In a stmt of a 'do' expression:
str <- readFile "/home/shk/workspace/lxmpp/src/test.txt"
In the expression:
do { str <- readFile "/home/shk/workspace/src/test.txt";
str }
谢谢。
【问题讨论】:
-
do-notation 中的 readFile 表示你在 IO monad 中,IO monad 无法转义!
-
@is7s 除非你使用
unsafePerformIO! -
unsafePerformIO 的第一条规则是你不要告诉任何人 unsafePerformIO!
-
@Thomas 哦,喜欢 Real World Haskell 打破了这条规则
-
@Thomas 除非他理解广义的前组合子态