【问题标题】:Haskell HDBC library: Is there an elegant way to convert between [SqlValue] and records?Haskell HDBC 库:是否有一种优雅的方式在 [SqlValue] 和记录之间进行转换?
【发布时间】:2018-07-22 18:34:40
【问题描述】:

由于我无法通过记录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)

这段代码看起来很难看,如果我更改Item 记录的长度,也需要更新,所以我想知道是否有一种巧妙的方法来概括这个想法。

【问题讨论】:

标签: haskell hdbc


【解决方案1】:

根据您使用的库,(Int, Int, String, ...) 类型可能已经有一个(例如sqlite-simpleFromRow 实例。如果您需要 Item 成为一种新类型,您可以使用 GeneralizedNewtypeDeriving 扩展来免费获取该实例。除此之外,您当然可以定义自己的类型类/辅助方法以使其更加 DRY。

【讨论】:

  • GeneralizedNewtypeDeriving 似乎对生产不安全。
猜你喜欢
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多