Skip to content

Instantly share code, notes, and snippets.

@Ahnfelt
Last active October 5, 2019 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ahnfelt/629b1fa14eadc2bf1214eb3ec575b558 to your computer and use it in GitHub Desktop.
Save Ahnfelt/629b1fa14eadc2bf1214eb3ec575b558 to your computer and use it in GitHub Desktop.
Curly brace ML
type Functor[T[_]] {
map[A, B](x : T[A], f : A -> B) : T[B];
}
type Monad[T[_]](functor : Functor[T]) {
flatten[A](x : T[T[A]]) : T[A];
pure[A](value : A) : T[A];
flatMap[A, B](x : T[A], f : A -> T[B]) : T[B] =
flatten(functor.map(x, f))
}
optionFunctor = Functor[Option] {
map[A, B](x : Option[A], f : A -> B) = switch(x) {
case Some(value) => Some(f(value))
case None => None
}
};
optionMonad = Monad[Option](optionFunctor) {
flatten[A](x : Option[Option[A]]) = switch(x) {
case Some(inner) => inner
case None => None
};
pure[A](value : A) =
Some(value);
};
type Sequence[T[_]](monad : Monad[T]) {
sequence[A](list : List[T[A]]) : T[List[A]] =
switch(list) {
case [] => []
case [x, ..xs] => monad.flatMap(x, v => [v, ..sequence(xs)])
};
}
optionSequence = Sequence[Option](optionMonad);
main(system : System) {
debug.log(optionSequence.sequence(
[Some(1), None, Some(2)]
))
}
@Ahnfelt
Copy link
Author

Ahnfelt commented Oct 1, 2019

Some more datatypes:

type Pair[A, B](first : A, second : B)

type List[A] {
    Empty
    Link(head : A, tail : List[A])
}

where the Pair type expands to type Pair[A, B] { Pair(first : A, second : B) }.

The reason being that all types are sum types, possibly with type parameters, and each sum type constructor has fields and methods. All types are uniformly defined like this, even though there is a bit of syntactic sugar for it too.

Note that values may contain type definitions. For type equality, check syntactic equality on (e.T) after name resolution. No general path dependent types for now - they seem to be hard to prove safe.

What about abstract datatypes (type members). Add it with path dependent types?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment