Skip to content

Instantly share code, notes, and snippets.

@owickstrom
Last active April 11, 2016 12:06
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 owickstrom/abbdf5ad81b317064c63d9df4badb8c0 to your computer and use it in GitHub Desktop.
Save owickstrom/abbdf5ad81b317064c63d9df4badb8c0 to your computer and use it in GitHub Desktop.
Protocols sketches for Oden
//----------//
// SEMIRING //
//----------//
// Types that support addition and multiplication.
protocol Semiring(a) {
add : a -> a -> a
zero : a
mul : a -> a -> a
one : a
}
// consider the `+` operator syntactic sugar for Semiring::add
// then this function...
f(x, y) = x + y
// ...translates and infers to:
f : forall a.
a -> a -> a
where Semiring(a)
f(x, y) = Semiring::add(x, y)
// Semiring instance for Maybe-wrapped semiring instances.
instance Semiring(Maybe(a)) where Semiring(a) {
add(m1, m2) = match (m1, m2) {
(Just(v1), Just(v2)) => Just(Semiring::add(x, y))
_ => Nothing
}
zero = Just(Semiring::zero)
add(m1, m2) = match (m1, m2) {
(Just(v1), Just(v2)) => Just(Semiring::mul(x, y))
_ => Nothing
}
one = Just(Semiring::one)
}
main() = match (Just 10) + (Just 11) {
Just(n) => println(n)
Nothing => println(":/")
}
//--------//
// ERRORS //
//--------//
// Protocol version of `error` type from Go.
protocol Error(e) {
Error : e -> string
}
protocol HasError(v) {
Error : v -> e where Error(e) // won't clash
}
printErr : forall e. e -> () where HasError(e)
printErr(err) = println(HasError::Error(err)) // Protocol is always qualified
instance Error(string) {
Error(s) = s
}
instance HasError(string) {
Error(s) = s
}
main() = printErr("Shit broke")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment