从dobe区块中的Maybe中提取值

时间:2018-08-12 15:12:08

标签: haskell

嗨,我有一段代码可以检索Maybe User,其中User是我自己的类型。

getUserById :: Int -> IO (Maybe User)
getUserById id = let userId = id in do
            conn <- createConnection
            (columnDef, inputStream) <- query conn selectByIdQuery [One $ MySQLInt32 (intToInt32 userId)]
            maybeMySQLValue <- Streams.read inputStream
            return (transformToUser <$> maybeMySQLValue)

但是关键是调用此函数的函数期望IO User而不是IO Maybe User

  

getUserById :: Int-> IO用户

关于如何在do块中提取Maybe值的任何建议? 我正在尝试这样做,但仍然无法正常工作

 user <- extractMaybeUser (transformToUser <$> maybeMySQLValue)
            return user

extractMaybeUser :: Maybe User -> User
extractMaybeUser maybeUser = case maybeUser of
     Just value -> value
     Nothing -> User 1 "default User"

致谢

1 个答案:

答案 0 :(得分:2)

user <- extractMaybeUser (transformToUser <$> maybeMySQLValue)

此代码可能不起作用的原因是extractMaybeUser的返回类型为User

extractMaybeUser :: Maybe User -> User

使用<-不能提取任何单价,那么仅将IO中获得的用户包裹在extractMaybeUser中呢?

return (extractMaybeUser (transformToUser <$> maybeMySQLValue))

它将至少具有IO User类型