簡體   English   中英

如何使用綁定和IO讀取Int重寫`do`塊?

[英]How to rewrite `do` block using bind with an IO read Int?

因此,我想使用>> / >>=綁定而不是do<-prog定的prog函數:

prog :: IO Int
     prog =
       do putStrLn "Hello there! How old are you?"
       age <- (readLn :: IO Int)
       let agedays = show $ age * 365
       putStrLn $ "So you are at least than " ++ agedays ++ " days old."
       return (read agedays)

重寫更簡單的功能對我來說不是問題,但是readLn :: IO Int讓我頭疼。

我的建議是:

prog :: IO Int
prog =
     putStrLn "Hello there!How old are you?" >>
     readLn::IO >>=
     let agedays = \age -> show $ age * 365 >>
     putStrLn $ "So you are at least than " ++ agedays ++ " days old."

但是,這是行不通的,因為將readLn :: IO綁定到下一個匿名函數\\age 有什么幫助嗎?

您正在改變的代碼太多,例如去除IntIO Int ,並插入錯誤的點lambda表達式。

這樣的事情應該起作用:

prog =
   putStrLn "Hello there! How old are you?" >>
   (readLn :: IO Int) >>= \age ->
   let agedays = show $ age * 365
   in putStrLn $ "So you are at least than " ++ agedays ++ " days old." >>
   return (read agedays)

您可以讓類型推斷為您完成工作,

prog :: IO Int
prog =
     putStrLn "Hello there! How old are you?" >>
     readLn >>= (\ age ->
     let agedays = age * 365 in
       putStrLn ("So you are at least " ++ show agedays ++ " days old.") >>
       return agedays )

由於您已經指定了prog :: IO Int ,因此意味着return agedays :: IO Intagedays :: Int

然后,這兩個操作數*age * 365必須是同一類型的,具體而言,是的agedays ,因為我們有agedays = age * 365那里。 因此,它已經遵循該age :: Int了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM