From f4afff43cd3f32d95336cd6f4ad17e715f553e7e Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Mon, 22 Nov 2021 23:32:55 -0600 Subject: [PATCH] type parameter inference rules are confusing --- list/iter.go | 49 +++++++++++++++++++++++++++++++++++++++++------ list/list_test.go | 2 ++ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/list/iter.go b/list/iter.go index db2a1cc..f03ff82 100644 --- a/list/iter.go +++ b/list/iter.go @@ -8,9 +8,46 @@ type Iter[T any] interface { Next(*T) bool } -/* -type Iter[T any] interface { - Done() bool - Next() T -} -*/ +// This actually works, but for some reason I don't yet understand, defining +// Max with a constraint of constrains.Ordered that takes Iterable[T] cannot +// have its type parameter infered, but defining it with the same constraint of +// constraints.Ordered and taking List[T] does allow the type parameter to be +// inferred. Super confusing. +// +// func Max[T constraints.Ordered](l Iterable[T]) T { +// it := l.Iter() +// +// var v T +// if !it.Next(&v) { +// return v +// } +// max := v +// for it.Next(&v) { +// if v > max { +// max = v +// } +// } +// return max +// } + + +// Discarded Iterator types: +// +// This was my first attempt. I like to have a method that returns a bool so +// you can use it succinctly in a for loop, but I didn't love having to call +// both done and next +// +// type Iter[T any] interface { +// Done() bool +// Next() T +// } +// +// I was never optimistic about this. In practice, using this in a for loop is +// just annoying so I stopped doing it. But also there's another thing I find +// annoying: it's a copy every time. You're not really iterating over the +// values, you're iterating over copies of the values, it seemed like a lot of +// unecessary copying. +// +// type Iter[T any] interface { +// Next() (T, bool) +// } diff --git a/list/list_test.go b/list/list_test.go index 0bd7e0d..b0686f6 100644 --- a/list/list_test.go +++ b/list/list_test.go @@ -110,7 +110,9 @@ func TestMap(t *testing.T) { eq(t, 20, nums.At(1)) eq(t, 30, nums.At(2)) eq(t, 0, nums.At(3)) + eq(t, 30, Max(nums)) + } func TestIter(t *testing.T) {