-
Notifications
You must be signed in to change notification settings - Fork 0
Guide Typeclasses
A good example of making a type an instance of a typeclass is the Maybe type built in to Translucent. It is defined as:
function Maybe(isNull, value) {
this.isNull = isNull;
this.value = value;
}Then if you wanted to make Maybe an instance of the Functor typeclass, you would define a map function for it:
function maybeMap(f, maybe) {
return maybe.isNull ? maybe : new Maybe(false, f(maybe.value));
}And then you would register it with Translucent:
tlc.addInstance(Maybe, {map: maybeMap});Translucent defines the following typeclasses (shown with the functions that must be defined in order to implement them):
- Applicative
- unit(type, value)
- ap(applicativeF, applicativeX)
- Contravariant
- contramap(f, contravariant)
- Functor
- map(f, functor)
- Monad
- unit(type, value)
- bind(monad)
- Monoid
- mempty(type)
- mappend(x, y)
- mconcat(xs)
- Functor
- Applicative
- Monad
- Applicative
- Contravariant
- Monoid
This means that if you instantiate Monad, your type will automatically be part of the Applicative and Functor typeclasses.
It's easy to define your own typeclass. Just define functions for that typeclass that use tlc.getInstanceFunc. For example, a Functor typeclass can be implemented like:
function map(f, functor) {
var map = tlc.getInstanceFunc(functor.constructor, "map");
return map(f, functor);
}A typeclass function usually just calls whichever function is registered for a type.