Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Associated Types #3

Closed
jamesgarfield opened this issue Dec 19, 2014 · 0 comments
Closed

Associated Types #3

jamesgarfield opened this issue Dec 19, 2014 · 0 comments

Comments

@jamesgarfield
Copy link
Contributor

Related Types

(renamed from associated types because apparently haskell has that already)

A Related Type is a type defined in generic code that does not need a matching type from the specification source because it is can be concretely implemented by the implementation of the other types in the generic code. A Related Type would also require an _ to be part of the name somewhere in order to avoid collisions with other implementations. The _ gets replaced with some inferred identifier.

In the following code _Sorter would be considered an associated type. By solving for Slice and T, _Sorter can be fully rewritten by selecting an identifier to replace the _ with

type T interface{}
type Slice []T
func (s Slice) Len() int { return len(s)}
func (s Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

type _Sorter struct {
    Slice
    LessFunc func(i, j *T) bool
}

func (s Slice) Less(i, j int) bool {
    return s.LessFunc(s.Slice[i], s.Slice[j])
}

Given these types

type User struct {
    Name string
    Age  int
}
type Users []*User

The expected implementation of _Sorter would be

type UsersSorter struct {
    Users
    LessFunc func(i, j *User) bool
}

func (s UsersSorter) Less(i, j int) bool {
    return s.LessFunc(s.Users[i], s.Users[j])
}

This effectively eliminates the need for multiple sorting types, and allows for concise adhoc sorting

sort.Sort(UsersSorter{users, func(a, b *User) bool { return a.Age < b.Age }})

or even

func (s Users) Sort(fn func(*User, *User) bool) {
    sort.Sort(UsersSorter{s, fn})
}
// time passes
users.Sort(func(a, b *User) bool { return a.Age < b.Age })

Possible _ replacement inference rules

  • First encountered specification type within the associated type (Users in the example)
  • Least complex type in the associated type (User in the example)
  • Most complex type in the associated type (Users in the example)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant