首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在地图/ forM中使用forM

在地图/ forM中使用forM
EN

Stack Overflow用户
提问于 2013-08-01 19:55:47
回答 1查看 224关注 0票数 2

列表中的每个元素都会触发一些DB更新,但我仍然坚持返回类型。你能告诉我什么是正确的方法吗?

代码语言:javascript
复制
for ::  [a] -> (a -> b) -> [b]
for xs f = map f xs

-- Summary: Loop over the elements of xs and update the table for each element
-- get an ID from the element
-- get the record corresponding to that ID
-- extract more values
-- update table (below is just a dummy updateWhere 
-- but the above values will be used in the update eventually )
forM_ xs $ \(Entity xid val) -> do
            let qid = tableField val 
            y <- runDB $ get404 qid
            let z = table2Field y
            return $ updateWhere [PersonName ==. "Test"] [PersonAge *=. 1] 

我得到以下错误:

代码语言:javascript
复制
Couldn't match type `PersistMonadBackend m0'
               with `persistent-1.2.1:Database.Persist.Sql.Types.SqlBackend'
Expected type: PersistMonadBackend m0
  Actual type: PersistEntityBackend Person
In the second argument of `($)', namely
  `updateWhere [PersonName ==. name] [PersonAge *=. 1]'

我尝试使用for而不是forM or forM_,但它没有修复任何问题。在这一点上,我只是尝试了一大堆组合,而没有真正理解如何修复这个错误。感谢你的帮助!

更新:

下面是我正在使用的实际代码。当我处理掉大多数let语句,只运行updateWhere时,只需进行简单的更新,它仍然会给出相同的错误。

代码语言:javascript
复制
getCalculateDeltaR :: personId -> Handler Html
getCalculateDeltaR personId = do

    goods <- runDB $ selectList [GoodPerson ==. personId] [] 

    forM goods $ \(Entity gid good) -> do
                let aid = goodAsset good  
                asset <- runDB $ get404 aid
                let mktValue = assetMktValue asset
                return $ updateWhere [GoodPerson ==. personId, GoodAsset = aid] [GoodDelta =. (mktValue - GoodOrigValue)]  

    defaultLayout $ do
        $(widgetFile "calculateDelta")

如果我将上面的forM更改为:

代码语言:javascript
复制
    forM goods $ \(Entity gid good) -> do
                return $ updateWhere [GoodPerson ==. personId] [GoodDelta =. 1]  

对于不匹配的类型,我仍然会遇到同样的错误。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-08-01 21:50:32

我不太熟悉yesod,但我认为下面的代码应该有效:

代码语言:javascript
复制
forM_ xs $ \(Entity xid val) -> do
        let qid = tableField val 
        y <- runDB $ get404 qid
        let z = table2Field y
        runDB $ updateWhere [PersonName ==. "Test"] [PersonAge *=. 1] 

您不希望返回DB操作,然后丢弃它们(forM_抛出单个返回值),因为这只会导致没有任何操作。你得管理他们。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18003343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档