On Tue, 11 Sep 2018 18:22:12 -0700
Patrick Smith <pat42sm...@gmail.com> wrote:

> I'm fairly sure there's no way to write Min, but perhaps someone can prove
> me wrong?

Within "Craftsman Go Generics" proposal its trivial:

func Min(a, b T) T {
  for type switch {
  case T func(T) Less(T) T:
      return a.Less(b)
  }
  if a < b {
       return a
  }
  return b
}

How does it work:

At compile time when compiler sees call to Min(a, b) with
any given type RTA compiler:

1. checks the first (and here single) case of whether T has
  Less method defined. If its true, then a Min variant of

  Min(a, b __TbyLess) __TbyLess {
            return a.Less(b)
  }
  
  is instantiated. "__TbyLess" denotes that its an internal compiler
  representation and reminds that only single piece/part of code will ever
  be produced out of single "for type switch" case.
 
2. If it does not (have Less method) "for type switch" case does not match
   so "it does not exist" in regards to current type check, so now we have  

  func Min(a, b __TbyOtherMeans) __TbyOtherMeans {
    if a < b {
       return a
    }
       return b
    }
  }

  Now if the type is NOT comparable, compiler says to us that we can not
  use Min with type RTA. (CGG  contracts operate on types, not on artificial
  statements).

  If RTA type is comparable, compiler makes variant of output code, hopefully
  marking it internally for reuse with wide class of base types.

  https://github.com/ohir/gonerics

> (With contracts I'm doubly sure it can't be done, as the contract for Min
> would have to permit both Less and <, so then Min(X) would only be allowed
> for types X having both Less and <.)

TC,

-- 
Wojciech S. Czarnecki
 << ^oo^ >> OHIR-RIPE

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to