【问题标题】:Meaning and usage of complex number functor and monad?复数函子和monad的含义和用法?
【发布时间】:2018-04-21 05:18:26
【问题描述】:

当我从 GHC Data.Complex 模块中阅读 Applicative ComplexMonad Complex 实例的源代码时,我有点惊讶:

-- | @since 4.9.0.0
instance Applicative Complex where
  pure a = a :+ a
  f :+ g <*> a :+ b = f a :+ g b
  liftA2 f (x :+ y) (a :+ b) = f x a :+ f y b

-- | @since 4.9.0.0
instance Monad Complex where
  a :+ b >>= f = realPart (f a) :+ imagPart (f b)

什么...? Applicative Complex 实例似乎将复数视为大小为 2 的数组。而且它们看起来更像是箭头操作。它们背后有什么数学基础吗?有没有,有什么用?

【问题讨论】:

  • 它们是守法的实例,所以它们没有理由不存在(这是“数学”基础)
  • 所以与复分析无关,复数在这里只是大小为 2 的数组?
  • 复数,在某种意义上,只是大小为2的数组。ℂ与ℝ²同构。

标签: haskell monads functor complex-numbers applicative


【解决方案1】:

编辑在底部添加注释:“线性”包。

实例是根据a mailing list post 发起的Trac 10609 ticket 添加的,其中 Fumiaki Kinoshita 注意到基础库中缺少一些似乎只能通过一种方式定义的实例,并提出了一个补丁来添加它们。

据我所知,将它们相加并没有数学动机,尽管至少有一个数学上有意义的运算可以应用表示,即标量乘法:

> pure (*) <*> pure 2 <*> (3 :+ 4)
6 :+ 8
>

在上述邮件列表帖子的 follow-up 中,Edward Kmett 指出他赞成,因为多年来他不得不将 Complex 的孤儿实例添加到他的 linear 包中以弥补缺失实例。

看起来他发现它们在为Complex 定义Additive 实例时很有用,因此基本上使Complex 成为二维向量的特例。

【讨论】:

  • 为什么使用pure f &lt;*&gt; pure a &lt;*&gt; b 而不是f a &lt;$&gt; b
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2012-10-11
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多