【问题标题】:How to iterate over values upon validation如何在验证时迭代值
【发布时间】:2021-09-25 22:16:35
【问题描述】:

我想构建一个简单的出价服务:

  1. 每个项目可以有多个出价。
  2. 每个投标都有一个对项目的引用和一个 Int price 字段。

创建新的出价后,我想确认它的价格高于现有的价格。

    action CreateBidAction = do
        let bid = newRecord @Bid
        bid
            |> buildBid
            |> validateIsPriceAboveOtherBids
            >>= ifValid \case
            -- ...
validateIsPriceAboveOtherBids bid = do
    item <- fetch (get #itemId bid)
    let highestBidPrice = gethighestBidPrice (get #bids item)
    bid
        |> validateField #price (isGreaterThan highestBidPrice)
        |> pure


gethighestBidPrice bids = 42

如果我尝试将bids 视为列表:gethighestBidPrice [] = 0

我收到一个错误:

Couldn't match type `[a0]' with `QueryBuilder "bids"'

我的问题是:

  1. 如果出价为空,如何在gethighestBidPrice 上将默认值设置为 0。
  2. 如何从出价中找出最高价。

【问题讨论】:

    标签: haskell ihp


    【解决方案1】:

    我似乎错过了get #bids itemfetch

    我是这样解决的:

    validateIsPriceAboveOtherBids bid = do
        item <- fetch (get #itemId bid)
        bids <- fetch (get #bids item)
    
        let prices = map (get #price) bids
        let highestBidPrice = maximum' prices
        bid
            |> validateField #price (isGreaterThan highestBidPrice)
            |> pure
        where
            maximum' :: [Int] -> Int
            maximum' [] = 0
            maximum' xs = foldr1 (\x y ->if x >= y then x else y) xs
    

    【讨论】:

      猜你喜欢
      • 2015-10-28
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2023-03-25
      相关资源
      最近更新 更多