【发布时间】:2014-05-12 22:21:11
【问题描述】:
目前,我在main 及其周围有这段代码:
import Control.Monad
import Control.Applicative
binSearch :: Ord a => [a] -> a -> Maybe Int
main = do
xs <- lines <$> readFile "Cars1.txt"
x <- getLine <* putStr "Registration: " -- Right?
putStrLn $ case binSearch xs x of
Just n -> "Found at position " ++ show n
Nothing -> "Not found"
我希望打印“Registration:”,然后程序等待x 的输入。我所写的是否意味着情况会如此?我需要<*,还是将putStr 表达式放在上面的行中也能正常工作?
PS:我知道我必须将 binSearch 转换为使用数组而不是列表(否则可能不值得进行二进制搜索),但这是另一天的问题。
【问题讨论】:
-
懒惰在这里发挥作用的唯一地方是
readFile,这是一种偷偷摸摸的功能——文件将在需要xs时被增量读取。其他一切——一般来说,IOmonad 中的所有操作(readFile、getContents除外,它们被明确写成惰性)将按照您对命令式语言的期望顺序执行。
标签: haskell io lazy-evaluation