這是來自https://haskell.mooc.fi/training 的練習
-- Ex 5: define the IO operation readUntil f, which reads lines from
-- the user and returns them as a list. Reading is stopped when f
-- returns True for a line. (The value for which f returns True is not
-- returned.)
--
-- Example in GHCi:
-- *Set11> readUntil (=="STOP")
-- bananas
-- garlic
-- pakchoi
-- STOP
-- ["bananas","garlic","pakchoi"]
readUntil :: (String -> Bool) -> IO [String]
readUntil f = todo
您能否使用 do 符號為我提供提示/解決方案?我是 do 符號的開始,“條件邏輯”以及回圈目前對我來說太復雜了。
太感謝了
uj5u.com熱心網友回復:
僅使用 do-notation 和條件陳述句,我找到了以下解決方案:
readUntil :: (String -> Bool) -> IO [String]
readUntil f = do x <- getLine;
if f x then (return []) else (do k <- readUntil f
return (x : k))
該函式首先讀取一行,getLine然后檢查是否(f x)為真。然后它只回傳空串列。我們不能只寫,... if f x then [] ...因為[]沒有型別IO [String]而只是[String]. 為了創建[]型別,IO [String]我們可以使用函式,return或者pure使用 do-notation 我使用return函式,因為它包含在Monad型別類中。如果f x等于,False我們然后使用第二個 do-block 遞回呼叫函式一次又一次,直到我們得到一個 Input f x == True,因此回傳空串列。do-notation 是必要的,因為 k 必須具有 type [String],但readUntil具有 type IO [String]。我們不能將:("cons") 運算子與型別的物件一起使用IO String因此無法生成我們想要的串列。然后我們將 x 添加到我們所有其他輸入的串列 k 中并回傳它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/393113.html
標籤:哈斯克尔
上一篇:||令牌是如何制作的在亞歷克斯
