【发布时间】:2014-04-28 05:02:03
【问题描述】:
这是一个特定于 Yesod 的问题,但即使您不知道 Yesod 也可以帮助我,它与新类型有关。
假设我的配置/模型中有以下简化模型
Value
userId UserId
weight Weight
deriving (Show)
我将在我的 web 应用程序中同时使用公斤和磅,但我决定数据库应该以公斤为单位存储东西。为了让类型系统避免混淆这两者,我定义了以下内容:
newtype Weight = Kilograms Int
deriving (Read, Show, Eq, PersistField, PersistFieldSql)
编译得很好,但是如何从表单中使用它?
logForm :: UserId -> Form Value
logForm uid = renderDivs $ Value <$>
pure uid <*>
areq intField "Weight" Nothing
我得到了错误
No instance for (Integral ModelTypes.Weight)
arising from a use of `intField'
我尝试派生Integral,但它抱怨我没有Real Weight。不断地,我最终得到:
newtype Weight = Grams Int
deriving (Read, Show, Eq, Enum, Ord, Num, Integral, Real, PersistField, PersistFieldSql)
这是正确的方法吗?好像有很多重复。有什么更好的方法?
一般来说,如果我在 Haskell 中有一个
newtype N = T a
对于具体类型a,我如何让N 重新派生a 的所有实例,并让N 派生一些其他类型类(在我的示例中为PersistField 和PersistFieldSql)。非常感谢。
【问题讨论】: