简体   繁体   English

如何使用绑定和IO读取Int重写`do`块?

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

So, I want to rewrite the given prog function with using >> / >>= bindings instead of do and <- : 因此,我想使用>> / >>=绑定而不是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)

Rewriting more simple functions is not a problem for me, but the readLn :: IO Int is giving me a headache... 重写更简单的功能对我来说不是问题,但是readLn :: IO Int让我头疼。

My suggestion was: 我的建议是:

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."

However this just does not work, as there is a problem with binding the readLn :: IO to the next anonymous function \\age . 但是,这是行不通的,因为将readLn :: IO绑定到下一个匿名函数\\age Any help? 有什么帮助吗?

You are changing the code too much, eg removing Int from IO Int , and inserting lambdas in the wrong points. 您正在改变的代码太多,例如去除IntIO Int ,并插入错误的点lambda表达式。

Something like this should work: 这样的事情应该起作用:

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)

You can let the type inference do the work for you, 您可以让类型推断为您完成工作,

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 )

Since you already specify prog :: IO Int , it means return agedays :: IO Int , and agedays :: Int . 由于您已经指定了prog :: IO Int ,因此意味着return agedays :: IO Intagedays :: Int

Then, both operands to * in age * 365 must be of the same type, specifically, that of agedays , since we have agedays = age * 365 there. 然后,这两个操作数*age * 365必须是同一类型的,具体而言,是的agedays ,因为我们有agedays = age * 365那里。 Thus it follows that age :: Int already. 因此,它已经遵循该age :: Int了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM