首页 > 解决方案 > 如何使用带有 IO 读取 Int 的绑定重写“do”块?

问题描述

所以,我想prog>>/>>=绑定而不是doand重写给定的函数<-

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。有什么帮助吗?

标签: functionhaskelliomonadsdo-notation

解决方案


您更改代码太多,例如从 中删除IntIO Int并将 lambdas 插入错误的点。

像这样的东西应该工作:

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)

推荐阅读