johnynek / bosatsu

A python-ish pure and total functional programming language
Apache License 2.0
224 stars 11 forks source link

design possible typeclasses for bosatsu #440

Open johnynek opened 4 years ago

johnynek commented 4 years ago

I'm in no rush to add typeclasses, but if I did, it might make sense to think about a design for a while.

Here is a design that occurred to me which might be an interesting starting point:

# we can mark some values as default values:
struct Order(to_Fn: a -> a -> Cmp)

default Order[Int]: Order(cmp_Int)

default Order[(a, b)] from default (ord_a: Order[a], ord_b: Order[b]):
    def ord_fn((a1, b1), (a2, b2)):
      match ord_a(a1, a2):
          EQ: ord_b(b1, b2)
          not_eq: not_eq

    Order(ord_fn)

#we can write functions that use defaults:
def min(left: a, right: a) default (ord: Order[a]) -> a:
    Order(cmp) = ord
    match cmp(left, right):
        LT: left
        _ : right

#now we can call min without giving the defaults:
min1 = min(1, 2)

To search for default values we could search the current package first, then search all the packages that have types in common with the default we need. If more than one is found, we can report and error and list the duplicates.

This would complicate type inference a bit, but it is manageable. I think the type of functions changes from a -> b to something like a default (b, c, d...) -> z where each function has a list of default values of certain types that it requires.

One interesting idea is the possibility of accepting functions that use defaults:

def foo(fn: Int default D -> Int) default (d: D) -> Int
    # we can call fn because there is a default d
    fn(0)

This is just a strawman starting point. I'm not at all certain this should be done. Maybe in a year or two if the need seems to persist.

johnynek commented 2 years ago

a simpler search proposal would be only search lexical scope and imports.

from Option import (mapOpt, default Order[Option[a]])