刚刚在练习写 Haskell 时,遇到个小问题,一时不解上来发问。
我想写一个 function 用来读 stdin 直到读到特定的字符
成功版:
getCharUntil :: Char -> IO [Char]
getCharUntil c = do x <- getChar
if x == c then return []
else do xs <- getCharUntil c
return $ x : xs
失败版:
sequenceWhile :: Monad m => (a -> Bool) -> [m a] -> m [a]
sequenceWhile f ms = sequence ms >>= return . takeWhile f
getCharUntil' c = sequenceWhile (/=c) $ repeat getChar
失败版会一直读不停
Lazy evaluation 很耐死的,一定是有什么误会…
感谢