Skip to content
Jonathan Potter edited this page Jun 9, 2014 · 8 revisions

Adding an Instance of a Typeclass

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});

List of Typeclasses

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)

Typeclass Hierarchy

  • Functor
    • Applicative
      • Monad
  • Contravariant
  • Monoid

This means that if you instantiate Monad, your type will automatically be part of the Applicative and Functor typeclasses.

Defining Your Own Typeclass

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.

API

  • [Array](API Array)
  • [Function](API Function)
  • [Maybe](API Maybe)
  • [Object](API Object)
  • [Set](API Set)
  • [Typeclass](API Typeclass)

Guides

  • [Operators](Guide Operators)
  • [Typeclasses](Guide Typeclasses)
  • [Replacing OOP](Guide Replacing Object Oriented Programming)

General

Clone this wiki locally