Skip to content

Instantly share code, notes, and snippets.

@neilvallon
Created August 19, 2015 12:05
Show Gist options
  • Save neilvallon/a9aff55a75eb66474f44 to your computer and use it in GitHub Desktop.
Save neilvallon/a9aff55a75eb66474f44 to your computer and use it in GitHub Desktop.
Generic ideas on peppering on some polymorphism
// I don't personally care about generics but everyone and their dog yells about them so
// it was impossible not to give some thought to how they might work in a go-ish way.
// this is just playing around with some syntax and seeing what semantics fall out.
// no idea what I'm doing. comments may be contradictory or idiotic.
// polygo is a dialect of go that live in a world free of angle bracketed capital letters.
package polygo
// enforce sameness of the method receiver and argument
type T comparable interface {
Cmp(a T) bool
}
// type (namedParam constraint) typeName struct {}
// constraints must be interface types
type (T interface{}) heap struct {
data []T
// T heap // what to do here
// maybe bind should produce a type in the compiler like:
// type intheap bind(heap, int)
//
// an alternative is to have the type itself say it holds interface{}
// but have methods that accept its own h.T
// this would make all generic types type be the same but allow them to
// implement a different set of interfaces depending on bind().
// heap {
// T: bind(heap, float64),
// }
}
func (h *Heap) Push(elm h.T) {
// type h.T is only accessible within methods defined on the same struct.
// the effective type of h.data inside this function is interface{} since that
// was the constraint placed on type h.T it from the type def.
}
func (h *Heap) Pop() elm h.T {}
func main() {
// add new builtin func bind(GT, T...) that takes a generic type and a variadic
// list of types to parameterize by.
//
// bind has new() semantics.
// the type of intheap is only heap. it is not parameterized in any way from the outside.
//
// as far as anyone knows the definition of heap is:
// type heap struct {
// data []interface{}
// }
var intheap heap = bind(heap, int) // or piggyback on make()
var i int = 0
intheap.data[0] = i // fails int is not type h.T
var x h.T = 0 // fails: what is h? not in scope is what it is.
var x intheap.T = 0 // fails: intheap has no struct member T
// succeeds! int(0) implements interface{}
var x heap.T = 0
intheap.data[0] = x // fails. but its still not type h.T
h.Push(i)
var j int = h.Pop()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment