剛剛在練習寫 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 很耐死的,一定是有什麼誤會…
感謝