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 )