I wanted to see if I could emulate the From
trait from Rust. I think a Purescript version (of this Rust source) looks like this:
class From source target where
from :: source -> target
This compiles just fine.
One of the things the Rust standard library provides is reflexivity for this trait (more rusty code here). That is, every type T
has an implementation From<T>
. My attempt at doing this in Purescript compiles just fine too:
instance fromSelf :: From source source where
from source = source
The problem comes when I try to implement something specific:
instance fromBooleanInt :: From Boolean Int where
from true = 1
from false = 0
Overlapping type class instances found for
Data.Convert.From Boolean
Int
The following instances were found:
Data.Convert.fromSelf
Data.Convert.fromBooleanInt
in type class instance
Data.Convert.From Boolean
Int
PureScript(OverlappingInstances)
Iām aware that the Purescript compiler doesnāt check constraints until it picks an instance. I also understand that I can use instance chains to fix this, though from my understanding that would prevent anyone outside this module from writing an instance for this class for their own types. But it feels weird to me that I get this error when I reuse the same type variable for each parameter in fromSelf
.
Could someone explain what the compiler is doing here? Does the fact that two variables are the same count as a constraint? Is there an example of something similar being done without instance chains, or is what Iām trying to do impossible?
Just wanted to mention that this is purely an academic exercise for me. I might be way too curious about these kinds of thingsā¦
⦠also, I actually ran into this when trying to write an instance for From Void target
. I donāt know if that has a different cause, but the From Boolean Int
case seemed simpler to start with while trying to understand things.