gpt4 book ai didi

haskell - 编写重载字符串时如何删除样板文件?

转载 作者:行者123 更新时间:2023-12-02 02:00:52 25 4
gpt4 key购买 nike

给定以下代码:

{-# 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

最佳答案

使用GeneralizedNewtypeDeriving并推导出 IsString Firstname 的实例和 Lastname .您的示例的示例代码如下

{-# 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 编写您想要的类似函数,但将这些函数保存在单独的模块中然后在此处导入它们是不值得的。

关于haskell - 编写重载字符串时如何删除样板文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17126087/

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