JoeDonald
JoeDonald

Reputation: 125

Adding two complex numbers in Haskell

I made the adding of two complex numbers in Haskell like this:

data Complex = C
{ realC :: Double
, imgC  :: Double
} deriving Show


addC :: Complex -> Complex -> Complex
addC (C a b) (C c d)= C (a+c) (b+d)

My question is: Can i make the above function (addC) point-free?

Upvotes: 2

Views: 1091

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152927

Yup:

addC = ap (ap . (C .) . (. realC) . (+) . realC) ((. imgC) . (+) . imgC)

Obviously I do not recommend this. You can learn this yourself by asking lambdabot to point-free-ify things in the #haskell IRC channel, or download and use it yourself from Hackage. This is the command I ran to get the above definition:

?pl addC l r = C (realC l + realC r) (imgC l + imgC r)

However, when doing it by hand, it is often possible to make more readable results. For example:

addC = liftA2 (liftA2 C) ((+) `on` realC) ((+) `on` imgC)

Even with this somewhat decipherable version, I would still strongly prefer the code you wrote; your code is simple, it's blazingly obvious what it does, and that style makes it hard to get the code wrong.

Upvotes: 3

Related Questions