在 Yesod 中将 PersistValue 转换为文本
convert PersistValue to Text in Yesod
我想从 Persist Entity 获取属性值;所以我有以下代码
userToText userId = do
user <- runDB $ get404 userId
userName user
这段代码无法编译,所以我写了那些替代版本
userToText userId = do
user <- runDB $ get404 userId
listToJSON [user]
userToText userId = do
(_,_,_,_,_,name,_,_) <- runDB $ get404 userId
show name
全部生成相同的错误
Handler/Report.hs:105:9:
Couldn't match expected type ‘HandlerT site IO b’
with actual type ‘Text’
Relevant bindings include
userToText :: Key PersistValue -> HandlerT site IO b
(bound at Handler/Report.hs:102:1)
In a stmt of a 'do' block: listToJSON [user]
In the expression:
do { user <- runDB $ get404 userId;
listToJSON [user] }
感谢您的帮助
您的代码在 Handler
monad 中,因此您的函数需要 return 类型 Handler Text
而不仅仅是 Text
:
userToText :: UserId -> Handler Text
userToText userId = do
user <- runDB $ get404 userId
return $ userName user -- Note the `return` here
(这类似于 getLine
等函数的类型是 IO String
而不是 String
)。
我想从 Persist Entity 获取属性值;所以我有以下代码
userToText userId = do
user <- runDB $ get404 userId
userName user
这段代码无法编译,所以我写了那些替代版本
userToText userId = do
user <- runDB $ get404 userId
listToJSON [user]
userToText userId = do
(_,_,_,_,_,name,_,_) <- runDB $ get404 userId
show name
全部生成相同的错误
Handler/Report.hs:105:9:
Couldn't match expected type ‘HandlerT site IO b’
with actual type ‘Text’
Relevant bindings include
userToText :: Key PersistValue -> HandlerT site IO b
(bound at Handler/Report.hs:102:1)
In a stmt of a 'do' block: listToJSON [user]
In the expression:
do { user <- runDB $ get404 userId;
listToJSON [user] }
感谢您的帮助
您的代码在 Handler
monad 中,因此您的函数需要 return 类型 Handler Text
而不仅仅是 Text
:
userToText :: UserId -> Handler Text
userToText userId = do
user <- runDB $ get404 userId
return $ userName user -- Note the `return` here
(这类似于 getLine
等函数的类型是 IO String
而不是 String
)。