我想在字段上定义约束,因此保留字无效。我怎样才能在Yesod中实现这一目标?
{-# LANGUAGE TemplateHaskell #-}
module Sid where
import Control.Exception
import Data.List
import Database.Persist.TH
import Data.Aeson.TH
import Text.Show
import Text.Read
import Data.Text
data Sid = Sid Text
deriving (Show, Read)
reserved :: [Text]
reserved = ["abc","def"]
allowedSid :: Text -> Sid
allowedSid a = (assert (notElem a reserved)) Sid a
derivePersistField "allowedSid"
deriveJSON defaultOptions ''allowedSid
答案 0 :(得分:3)
我会在普通的Haskell中执行此操作:使用一些智能构造函数创建一个newtype包装器。这看起来像是:
newtype Sid = Sid Text
mkSid :: Text -> Maybe Sid
mkSid t = if t `elem` reserved then Nothing else Just t
将此代码放在模块中,不要导出Sid
数据构造函数。