gpt4 book ai didi

entity - Yesod/持久实体派生显示

转载 作者:行者123 更新时间:2023-12-04 20:44:25 26 4
gpt4 key购买 nike

Persistent chapter of the Yesod book , 一个例子给出了这个实体

{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, GADTs #-}
import Database.Persist
import Database.Persist.TH
import Database.Persist.Sqlite
import Control.Monad.IO.Class (liftIO)

mkPersist sqlSettings [persist|
Person
name String
age Int
deriving Show
|]

生成代码
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, OverloadedStrings, GADTs #-}
import Database.Persist
import Database.Persist.Store
import Database.Persist.Sqlite
import Database.Persist.GenericSql.Raw (SqlBackend)
import Database.Persist.EntityDef
import Control.Monad.IO.Class (liftIO)
import Control.Applicative

data Person = Person
{ personName :: String
, personAge :: Int
}
deriving (Show, Read, Eq)

type PersonId = Key Person

instance PersistEntity Person where
-- A Generalized Algebraic Datatype (GADT).
-- This gives us a type-safe approach to matching fields with
-- their datatypes.
data EntityField Person typ where
PersonId :: EntityField Person PersonId
PersonName :: EntityField Person String
PersonAge :: EntityField Person Int

type PersistEntityBackend Person = SqlBackend

toPersistFields (Person name age) =
[ SomePersistField name
, SomePersistField age
]

fromPersistValues [nameValue, ageValue] = Person
<$> fromPersistValue nameValue
<*> fromPersistValue ageValue
fromPersistValues _ = Left "Invalid fromPersistValues input"

-- Information on each field, used internally to generate SQL statements
persistFieldDef PersonId = FieldDef
(HaskellName "Id")
(DBName "id")
(FTTypeCon Nothing "PersonId")
[]
persistFieldDef PersonName = FieldDef
(HaskellName "name")
(DBName "name")
(FTTypeCon Nothing "String")
[]
persistFieldDef PersonAge = FieldDef
(HaskellName "age")
(DBName "age")
(FTTypeCon Nothing "Int")
[]

为什么添加 deriving Show到 Person 实体生成所有三个类型类的派生 (Show, Read, Eq) ?我对 Haskell 和 Yesod 很陌生,所以如果很明显,我很抱歉,但我在任何地方都找不到答案!这只是文档中的错误吗?谢谢!

最佳答案

很简单:这是书中的一个错字:)。如果您查看实际生成的代码(使用 -ddump-splices ),您会发现它实际上只是派生了 Show实例。

关于entity - Yesod/持久实体派生显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com