[英]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. 您正在改变的代码太多,例如去除
Int
从IO 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 Int
和agedays :: 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.