8

给定以下代码:

{-# LANGUAGE OverloadedStrings #-}

newtype Firstname = Firstname String deriving (Eq, Show)
instance IsString Firstname where fromString = Firstname

newtype Lastname = Lastname String deriving (Eq, Show)
instance IsString Lastname where fromString = Lastname

data Person = Person { firstname :: Firstname, lastname :: Lastname, age :: Int } deriving Show

我想删除围绕创建强类型字符串的样板。是否可以使用 Template Haskell(或其他方式)来实现这一点?

例如:

{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}

$(strongString ''Firstname)
$(strongString ''Lastname)

data Person = Person { firstname :: Firstname, lastname :: Lastname, age :: Int } deriving Show
4

1 回答 1

15

使用GeneralizedNewtypeDeriving并派生 和的IsString实例。您的示例的示例代码如下FirstnameLastname

{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-}
import Data.String

newtype Firstname = Firstname String deriving (Eq, Show, IsString)

newtype Lastname = Lastname String deriving (Eq, Show, IsString)

data Person = Person { firstname :: Firstname
                     , lastname :: Lastname
                     , age :: Int
                     }

foo = Person "hello" "world" 10

您可以使用 TH 编写您想要的类似函数,但将这些函数保存在单独的模块中然后在此处导入它们是不值得的。

于 2013-06-15T17:30:59.227 回答