【发布时间】:2011-09-01 02:24:25
【问题描述】:
在 Haskell 中,我可以轻松定义一个递归函数,它接受一个值并返回一个字符串:
Prelude> let countdown i = if (i > 0) then (show i) ++ countdown (i-1) else ""
Prelude> countdown 5
"54321"
我想使用相同的设计从文件句柄中读取可用数据。在这种特殊情况下,我需要以与 hGetContents 相同的方式读取数据,但不要让句柄处于“半关闭”状态,这样我就可以与使用 createProcess 打开的进程的 stdin/stdout 句柄进行循环交互:
main = do
-- do work to get hin / hout handles for subprocess input / output
hPutStrLn hin "whats up?"
-- works
-- putStrLn =<< hGetContents hout
putStrLn =<< hGetLines hout
where
hGetLines h = do
readable <- hIsReadable h
if readable
then hGetLine h ++ hGetLines h
else []
给出错误:
Couldn't match expected type `IO b0' with actual type `[a0]'
In the expression: hGetLine h : hGetLines h
我知道有各种库可用于完成我想要完成的工作,但是我正在学习我的问题实际上是如何执行递归 IO。蒂亚!
【问题讨论】:
标签: haskell recursion io monads lazy-evaluation