From cd94396df4cd06a953db717323d0d408c5b1e501 Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Tue, 23 Nov 2021 03:58:55 +0000 Subject: [PATCH] goofin around --- list/iter.go | 16 ++++++++++++++++ list/list.go | 37 +++++++++++++++++++++++++++++++++++++ list/list_test.go | 7 +++++++ 3 files changed, 60 insertions(+) create mode 100644 list/iter.go diff --git a/list/iter.go b/list/iter.go new file mode 100644 index 0000000..db2a1cc --- /dev/null +++ b/list/iter.go @@ -0,0 +1,16 @@ +package list + +type Iterable[T any] interface { + Iter() Iter[T] +} + +type Iter[T any] interface { + Next(*T) bool +} + +/* +type Iter[T any] interface { + Done() bool + Next() T +} +*/ diff --git a/list/list.go b/list/list.go index 3a8434b..51ad06b 100644 --- a/list/list.go +++ b/list/list.go @@ -110,6 +110,43 @@ func (l List[T]) Len() int { return i } +type iter[T any] struct { + n *node[T] +} + +func (i iter[T]) Done() bool { return i.n == nil } + +func (i *iter[T]) Next(dest *T) bool { + if i.n == nil { + return false + } + + *dest = i.n.val + i.n = i.n.next + return true +} + +func (l List[T]) Iter() Iter[T] { + return &iter[T]{n: l.head} +} + +// This doesn't work but I wish it did: +// +// func (l List[T comparable]) Max() T { +// if l.Empty() { +// var v T +// return v +// } +// +// v := l.head.val +// for n := l.head.next; n != nil; n = n.next { +// if n.val > v { +// v = n.val +// } +// } +// return v +// } + // Map applies the input function f to each element of the list l, returning a // new list containing the values produced by f func (l List[T]) Map(f func(T) T) List[T] { diff --git a/list/list_test.go b/list/list_test.go index 54ac56a..a8d1cf5 100644 --- a/list/list_test.go +++ b/list/list_test.go @@ -111,3 +111,10 @@ func TestMap(t *testing.T) { eq(t, 30, nums.At(2)) eq(t, 0, nums.At(3)) } + +func TestIter(t *testing.T) { + nums := Make(2, 4, 6) + for it, n := nums.Iter(), 0; it.Next(&n); { + t.Logf("%v", n) + } +}