I'm now working with PureScript on a project and came across instances (I'm a newbie, and am learning as I do). Basically I had to create an instance in order to overload a function with different types.
public String toStr(Integer i) {
return String.valueOf(i);
}
public String toStr(Float i) {
return String.valueOf(i);
}
(I know, this is weird one, but just for an example). This can be written using a type class as far as I understand.
foreign import unsafeToStr :: forall a. a -> String
class ToStr a where
toStr :: a -> String
instance intToStr :: ToStr Int where
toStr a = unsafeToStr a
instance numToStr :: ToStr Number where
toStr a = unsafeToStr a
This is how we do. As far as I know, there is no need to have a name to an instance, as the compiler automatically figures it out. I even tested it out of curiosity, and it worked for any name I gave it.
So why do instances of type classes in PureScript have names?
According to the book PureScript by Example, it is because:
in PureScript, type class instances are named to aid the readability of the generated JavaScript.
But I think you are correct and the name has no meaning whatsoever, and could arguably be generated by the compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With