【问题标题】:Adding maybeness to a Haskell data type (with record syntax)向 Haskell 数据类型添加可能性(使用记录语法)
【发布时间】:2018-12-27 09:10:36
【问题描述】:

查看这个问题的答案:

https://stackoverflow.com/a/34164251/1052117

我看到它定义了一种用于解析 JSON 对象的数据类型。

data Address = Address
    { house  :: Integer
    , street :: String
    , city   :: String
    , state  :: Maybe String
    , zip    :: String -- here I change the original, zip codes are strings, they have leading zeros.
    } deriving (Show, Eq)

$(deriveJSON defaultOptions ''Address)

这很有帮助,但我想知道:如何更改地址数据类型以使所有 json 字段都可以为空?具体来说,我在 state 字段之前看到了一个 Maybe,但我在想象一个更大的数据结构,在其中将所有字段修改为 Maybe 字段会很乏味。例如,虽然我/可以/将上面重写为:

data Address = Address
    { house  :: Maybe Integer
    , street :: Maybe String
    , city   :: Maybe String
    , state  :: Maybe String
    , zip    :: Maybe String
    } deriving (Show, Eq)

我可以对地址数据类型 /in code/ 应用什么函数来实现相同的结果,而无需重写所有代码并手动插入 Maybes?

【问题讨论】:

标签: haskell maybe


【解决方案1】:

正如 cmets 中所讨论的,使用 functor-functor 只需对原始数据类型进行非常小的更改即可解决此问题。

如果你从

开始
data Address = Address
    { house  :: Integer
    , street :: String
    , city   :: String
    , state  :: Maybe String
    , zip    :: String
    } deriving (Show, Eq)

那么就等价于

import Data.Functor.Identity

data AddressF f = Address
  { house  :: f Integer 
  , street :: f String
  , city   :: f String
  , state  :: Maybe String
  , zip    :: f String 
  } deriving (Show, Eq)

type Address = AddressF Identity

然后你可以通过写得到第二个

type Address' = AddressF Maybe

要回到原来的定义,你可以写

toOriginal (AddressF (Identity house) (Identity street) (Identity city) mbState (Identity zip)) = Address house street city mbState zip

【讨论】:

  • AddressF可以像原来的Address类型一样使用吗?例如,可以复制原件的身份 f 是什么?
  • 你可以在 AddressF 上编写函数,就像你做其他任何事情一样,就像你可以拥有 :: AddressF f -> f (String, Integer) 的东西一样,但它总是在函子上是多态的。编辑以更清楚地了解原始地址和我提供的地址之间的关系。
【解决方案2】:

无需手动重写所有代码即可获得相同的结果 插入Maybes

为了避免对记录类型的侵入性更改,我们可以通过分析其结构来处理从记录中派生的另一种类型,这需要相对高级的通用和类型级编程。此答案使用generics-sop 包。

一些必需的编译指示和导入:

{-# LANGUAGE DataKinds, TypeFamilies, FlexibleInstances, UndecidableInstances, 
             ScopedTypeVariables, TypeApplications, TypeOperators, 
             DeriveGeneric, StandaloneDeriving, MultiParamTypeClasses,
             FunctionalDependencies, AllowAmbiguousTypes, FlexibleContexts #-}
import           Data.Kind (Type)
import           Data.Type.Equality (type (==))
import           GHC.TypeLits
import qualified GHC.Generics as GHC
import           Generics.SOP -- from package "generics-sop"
import qualified Generics.SOP.Type.Metadata as M

这个新类型表示从记录派生的字段值的n-ary product,每个都包含在函子f 中。字段names 的类型级列表ns 保留为phantom type variable:

newtype Wrapped f (ns :: [Symbol]) (xs :: [Type]) = Wrapped { unwrap :: NP f xs }

deriving instance All (Generics.SOP.Compose Show f) xs => Show (Wrapped f ns xs)

type family FieldNamesOf (a :: M.DatatypeInfo) :: [Symbol] where
    FieldNamesOf ('M.ADT moduleName datatypeName '[ 'M.Record constructorName fields ]) = 
        ExtractFieldNames fields

type family ExtractFieldNames (a :: [M.FieldInfo]) :: [Symbol] where
    ExtractFieldNames '[] = '[]
    ExtractFieldNames (('M.FieldInfo n) ': xs) = n ': ExtractFieldNames xs

fromRecord :: forall r ns xs.  (IsProductType r xs, 
                                HasDatatypeInfo r, 
                                FieldNamesOf (DatatypeInfoOf r) ~ ns)
           => r 
           -> Wrapped I ns xs 
fromRecord r = let (SOP (Z np)) = from r in Wrapped np

toRecord :: forall r ns xs.  (IsProductType r xs, 
                              HasDatatypeInfo r, 
                              FieldNamesOf (DatatypeInfoOf r) ~ ns)
         => Wrapped I ns xs 
         -> r
toRecord (Wrapped np) = to (SOP (Z np))

如果我们不需要保留字段名称,newtype 就变得多余了,最好直接使用 n 元乘积 NP,使用 generics-sop 提供的 rich set of functions 操作它。

但如果我们确实想保持按名称选择字段的能力,那么我们需要在新类型上定义一个函数,由一对类型类支持:

getWrappedField :: forall n f ns xs x. HasField ns n xs x => Wrapped f ns xs -> f x
getWrappedField (Wrapped np) = getHasField @ns @n np  

class HasField (ns :: [Symbol]) (n :: Symbol) 
               (xs :: [Type])   (x :: Type)   | ns n xs -> x where 
    getHasField :: NP f xs -> f x 

instance ((e == n) ~ flag, HasField' flag (e : ns) n xs x) => HasField (e : ns) n xs x where
    getHasField = getHasField' @flag @(e : ns) @n

class HasField' (flag :: Bool) 
                (ns :: [Symbol]) (n :: Symbol) 
                (xs :: [Type]) (x :: Type)     | ns n xs -> x where 
    getHasField' :: NP f xs -> f x 

instance HasField' True (n : ns) n (x : xs) x where
    getHasField' (v :* _) = v

instance HasField ns n xs x => HasField' False (nz : ns) n (xz : xs) x where
    getHasField' (_ :* rest) = getHasField @ns @n rest

给定这个派生necessarysupportingtypeclasses的示例记录:

data Person = Person { name :: String, age :: Int } deriving (Show, GHC.Generic)
instance Generic Person
instance HasDatatypeInfo Person

我们可以构造它的广义表示(其中所有字段最初都包装在身份函子 I 中),然后获取其中一个字段,如下所示:

ghci> getWrappedField @"age" (fromRecord (Person "Jimmy" 25))
I 25

字段名称作为类型级别Symbol 传递,使用type application。

【讨论】:

  • 这与records-sop 包的作用有很大的重叠。
  • @kosmikus 啊,我看过records-sop,但不知何故错过了IsElemOf 类型类!作为这个答案的产物,我正在开发一个包,它定义由类型级玫瑰树github.com/danidiaz/red-black-record 索引的记录和变体@ 它搭载sop-core,并使用records-sop 中的技术来避免重叠实例。
猜你喜欢
  • 2010-12-26
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-09-10
  • 2022-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多