【问题标题】:Lenses with Sum Types (that have Product types)具有总和类型的镜头(具有产品类型)
【发布时间】:2016-04-19 20:41:55
【问题描述】:
{-# LANGUAGE TemplateHaskell      #-}

import Control.Lens

data Fruit = Fruit
  { _fruitColor :: String
  }

$(makeClassy ''Fruit)

data Fruits =
    Banana Int Fruit
  | Strawberry String Fruit

printer :: HasFruit s => s -> IO ()
printer f = putStrLn $ f ^. fruitColor

sample :: IO ()
sample = do
  printer $ Fruit "yellow"
  printer $ Banana 5 $ Fruit "yellow"

我有一个核心产品类型,水果。我希望拥有所有包含核心产品类型 Fruit 的数据类型,但希望能够用总和类型 Fruits 来表示它们。使用 sum 类型 Fruits,我希望能够访问核心产品类型 Fruits 的组件。也就是说,我希望像 Banana 和 Strawberry 这样的类型成为 HasFruit 的一个实例。

有没有一种直接的方法让 Fruits 实例化 HasFruit?有没有更好的模式来表示这个 - 总和类型的核心产品类型?

【问题讨论】:

  • 不知道lens包能不能导出这样的实例,不过你可以自己写:instance HasFruit Fruits where fruit k (Banana x f) = Banana x <$> k f ; fruit k (Strawberry x f) = Strawberry x <$> k f。应该注意的是Banana 和Strawberry 是not 类型——并且不能作为类的实例,因为它们不是类型。它们是返回 Fruit 类型值的构造函数。

标签: haskell haskell-lens


【解决方案1】:

这样做会更有意义:

data FruitType = Banana Int | Strawberry String

data Fruits = Fruits { _fruitsFruitType :: FruitType, _fruitsFruit :: Fruit }

makeFields ''Fruits

-- `Fruits` now instantiates `HasFruit`

您可能还想为FruitType 制作棱镜。 Prism 本质上是遍历 sum 类型的不同部分,但它们也可以用于构造它。

makePrisms ''FruitType

-- double the int if the argument is a `Banana`

doubleBanana = fruitType._Banana *~ 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-15
    • 2018-11-27
    • 1970-01-01
    • 2015-11-07
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多