嗨,我有一段代码可以检索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"
致谢
答案 0 :(得分:2)
user <- extractMaybeUser (transformToUser <$> maybeMySQLValue)
此代码可能不起作用的原因是extractMaybeUser
的返回类型为User
:
extractMaybeUser :: Maybe User -> User
使用<-
不能提取任何单价,那么仅将IO
中获得的用户包裹在extractMaybeUser
中呢?
return (extractMaybeUser (transformToUser <$> maybeMySQLValue))
它将至少具有IO User
类型