Function 如何使用bind和IO read Int重写'do'块?

Function 如何使用bind和IO read Int重写'do'块?,function,haskell,io,monads,do-notation,Function,Haskell,Io,Monads,Do Notation,因此,我想重写给定的prog函数,使用>>=绑定而不是do和您更改代码太多,例如从IO Int中删除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

因此,我想重写给定的
prog
函数,使用
>
>=绑定而不是
do
您更改代码太多,例如从
IO Int
中删除
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
,这意味着
返回agedays::IO Int
agedays::Int

然后,在
age*365
*
的两个操作数必须是相同的类型,特别是
agedays
的操作数,因为这里有
agedays=age*365
。因此,它已经是
age::Int

它不应该是
(readLn::IO Int)>=\age->…
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 )