The concept of using operators to implement methods cross-pollinated in my mind 
with Patrick’s “Go Generics with Adaptors” thought experiment and produced 
this: https://gist.github.com/andybalholm/acecba3acf57bf1254142dadce928890 
<https://gist.github.com/andybalholm/acecba3acf57bf1254142dadce928890>

Here is the core of the proposal (the gist of the gist?):

Contracts

In this proposal, a contract is a list of type-specific functions that are 
needed to implement a generic algorithm. Generally, it will contain default 
implementations for these functions, but these are optional. (If default 
implementations are not included, an adapter will always be necessary.) The 
default implementations are unconstrained generic code; if they compile 
successfully with a given set of type parameters, those parameters fulfill the 
contract.

contract Adder(T) {
        Zero() T {
                return 0
        }
        Add(a, b T) T {
                return a + b
        }
}
A generic function that uses a contract calls the functions in the contract to 
perform operations on generic values:

func SumSlice(type T Adder)(s []T) T {
        sum := Zero()
        for _, t := range s {
                sum = Add(sum, t)
        }
        return sum
}
 
<https://gist.github.com/andybalholm/acecba3acf57bf1254142dadce928890#adaptors>Adaptors

A type that doesn't work with a contract's default implementation can still 
fulfill the contract by means of an adaptor. An adaptor is a type that fulfills 
the interface defined by a contract. When an adaptor is being used, calls to 
the contract’s functions are implemented by calls to the corresponding methods 
of the adaptor’s zero value.

type BigIntAdder struct {}
func (BigIntAdder) Zero() *big.Int { return new(big.Int) }
func (BigIntAdder) Add(a, b *big.Int) *big.Int { return new(big.Int).Add(a, b) }
The adaptor is specified along with the type parameters when instantiating a 
generic function or type:

var bigints []*big.Int
fmt.Println(SumSlice(*big.Int, BigIntAdder)(bigints))
Andy

-- 
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