haskellmonadsfunctorcomplex-numbersapplicative

Meaning and usage of complex number functor and monad?


I was kinda surprised when I read the source code of instances of Applicative Complex and Monad Complex from GHC Data.Complex module:

-- | @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)

What the...? The Applicative Complex instance seems to treat complex numbers as just size-two arrays. And they both seem more like arrow operations. Is there any mathematical basis behind them? Either there is or not, what are they used for?


Solution

  • Edited to add note at bottom re: "linear" package.

    The instances were added as per this Trac 10609 ticket initiated by a mailing list post where Fumiaki Kinoshita noted that there were some missing instances in the base libraries that seemed to be definable in only one way and proposed a patch to add them.

    As far as I can see, there was no mathematical motivation for adding them, though there's at least one mathematically meaningful operation that can be expressed applicatively, namely scalar multiplication:

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

    In a follow-up to the above mailing list post, Edward Kmett noted that he was in favor because he'd had to add orphan instances for Complex to his linear package for years to make up for the missing instances.

    It looks like he found them useful in defining an Additive instance for Complex thus essentially making a Complex a special case of a two dimensional vector.