【问题标题】:Combined type = one, the other, or both?组合类型 = 一种、另一种或两者兼而有之?
【发布时间】:2015-03-31 04:39:31
【问题描述】:

我想知道这在 Haskell 中是否可行:

type DateTime = Date | Time | Date :+ Time

...因此它可以是特定日期、特定时间或由两者组成的复杂值。

【问题讨论】:

  • 切入重点:Data.These
  • 顺便说一句,“将DateTime 值捆绑在一起”实际上是这两种类型的产品,而不是总和。作为 ADT,你想要的写成 DateTime = Date + Time + Date × Time,或者在 Haskell 中写成 Either (Either Date Time) (Date, Time)。但是,最好像 AJFarmar 那样使用 data 定义类型,或者使用 These
  • 我认为Time 是一个虚构的Date (Time = Date × sqrt(-1)):P

标签: haskell types algebraic-data-types


【解决方案1】:

你刚刚成功了——当然有可能!

这就是我要做的:

data Both a b
    = First a
    | Second b
    | Both a b

有趣的是,这是一个双函子:

import Data.Bifunctor

instance Bifunctor Both where
    bimap f _ (First a)  = First (f a)
    bimap _ g (Second b) = Second (g b)
    bimap f g (Both a b) = Both (f a) (g b)

正如J. Abrahamson 所说,Data.These 包中有一个名为These 的类型,其中包括MonadBifunctor 实例,以及一些很棒的类型类实例,如BifoldableBitraversable完全值得一看。

【讨论】:

  • 日期时间事物的递归表示的问题,它可能有多个递归级别,这是没有意义的。
  • @EugeneSh。递归是什么意思?
  • Both a b 可以包含Both (Both a b) (Both a b) 吗?看起来像data Tree a b = Leaf a | Leaf b | Tree a b
  • @Mark Cidade ab 可以代表任何类型 - 为什么不呢?但是那种树型有点不对劲,再试一次!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
相关资源
最近更新 更多