zeropurescript

Purescript Complex zero element (Purescipt by example exercies)


I solve Purescript exercise from the book https://book.purescript.org/chapter6.html#multi-parameter-type-classes

I don't understand what "zero" statement is?

I have "Complex" type, and should define Semiring Complex instance of it.

newtype Complex
= Complex
 { real :: Number
 , imaginary :: Number
 }

Simple solution to define zero complex element (0.0+0.0i) as

instance semiringComplex :: Semiring Complex where
  zero = Complex {real: 0.0, imaginary: 0.0}

But another solution, presented in this book is

instance semiringComplex :: Semiring Complex where
 zero = Complex zero

I do not understand, how does this statement work ("Complex zero"), if zero defined as function (not as a Complex type element)

> :t zero
forall (a :: Type). Semiring a => a

And what I found tricky is

cz = Complex zero 
> cz
0.0+0.0i

How does PSCI understand that zero is 0.0+0.0i, but I did not define 0.0 constants?


Solution

  • zero is a method of the Semiring class. So it works for any type for which there is an instance of that class.

    It just so happens that there is an instance of the Semiring class for Record r - that is, for records. As long as there are Semiring instances for all the record's field types. And the way that instance is defined is that zero is a record with all fields set to their respective zero values.

    So, for example:

    (zero :: { x :: Int, y :: Unit }) == { x: 0, y: unit }
    

    Because (zero :: Int) == 0 and (zero :: Unit) == unit

    Or, in your particular case:

    (zero :: { real :: Number, imaginary :: Number }) == { real: 0.0, imaginary: 0.0 }
    

    Because (zero :: Number) == 0.0

    Which means that writing Complex zero is equivalent to writing Complex { real: 0.0, imaginary: 0.0 }