开发者

something like database but not a database and sum price

How can I sum prices where month = 5 and year = 2010 ? I have date in data Subject and prices in data Sell, they are connected by id. This is my code:

-- subject id, date
data Su开发者_JS百科bject = Subject Int CalendarTime deriving (Read, Show)

-- sell id, subject id, price
data Sell = Sell Int Int Double deriving (Read, Show)


Real world uses should probably use a database or at least a mapping (from the containers or unordered-containers packages), but a simple solution can be obtained using simple list comprehension.

Assuming you have simple lists of Subject and Sell:

type Subjects = [Subject]
type Sells = [Sell]

You could make an O(n*m) implementation (good for play only!):

 price :: Sell -> Double
 price (Sell _ _ d) = d

 calTime :: Subject -> CalendarTime
 calTime (Subject _ c) = c

 sIdent :: Subject -> Int  -- Omitted, you should use record syntax anyway
 eIdent :: Sell -> Int  -- Omitted

 sumPred :: (CalendarTime -> Bool) -> Subjects -> Sells -> Double
 sumPred js es = sum [price e | j <- js, e <- es
                     , sIdent j == eIdent e
                     , pred (calTime j)]

But as I said, that's foolish. Using a DB with Subjects keyed by CalendarTime and Sell's keyed by identity will give you a more practical solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜