[英]Haskell HDBC library: Is there an elegant way to convert between [SqlValue] and records?
Since I can't map
over a record, the best method I have found is to just use brute force: 由于我无法map
记录,因此发现的最佳方法是仅使用蛮力:
data Item = Item {
vendor :: Int,
lotNumber :: Int,
description :: String,
reserve :: Maybe Double,
preSaleBids :: Maybe Double,
salePrice :: Maybe Double,
purchaser :: Maybe Int,
saleID :: Maybe Int
}
hsToDb :: Item -> [SqlValue]
hsToDb (Item a b c d e f g h) = [toSql a, toSql b, toSql c, toSql d, toSql e, toSql f, toSql g, toSql h]
dbToHs :: [SqlValue] -> Item
dbToHs [a,b,c,d,e,f,g,h] = Item (fromSql a) (fromSql b) (fromSql c) (fromSql d) (fromSql e) (fromSql f) (fromSql g) (fromSql h)
This code looks ugly and also requires updating if I change the length of my Item
record so I was wondering whether there's a clever way of generalizing this idea. 如果我更改Item
记录的长度,那么这段代码看起来很丑陋,并且还需要更新,因此我想知道是否存在一种巧妙的方法来概括这个想法。
Depending on what library you're using the type (Int, Int, String, ...)
may already have a (as in eg sqlite-simple
) FromRow
instance. 根据您所使用的库的类型(Int, Int, String, ...)
可能已经具有(例如,在sqlite-simple
) FromRow
实例。 If you need Item
to be a new type you can use the GeneralizedNewtypeDeriving
extension to get that instance for free. 如果您需要Item
为新类型,则可以使用GeneralizedNewtypeDeriving
扩展免费获取该实例。 Barring this you could of course define your own type class/helper method to make it more DRY. 除此以外,您当然可以定义自己的类型class / helper方法以使其更干燥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.