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?
zerois a method of theSemiringclass. 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
Semiringclass forRecord r- that is, for records. As long as there areSemiringinstances for all the record's field types. And the way that instance is defined is thatzerois a record with all fields set to their respectivezerovalues.So, for example:
Because
(zero :: Int) == 0and(zero :: Unit) == unitOr, in your particular case:
Because
(zero :: Number) == 0.0Which means that writing
Complex zerois equivalent to writingComplex { real: 0.0, imaginary: 0.0 }