defined max

master
Jordan Orelli 3 years ago
parent cd94396df4
commit 4598d396db

@ -3,6 +3,7 @@ package list
import ( import (
"strings" "strings"
"sync" "sync"
"constraints"
"fmt" "fmt"
) )
@ -130,9 +131,24 @@ func (l List[T]) Iter() Iter[T] {
return &iter[T]{n: l.head} return &iter[T]{n: l.head}
} }
func Max[T constraints.Ordered](l List[T]) 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
}
// This doesn't work but I wish it did: // This doesn't work but I wish it did:
// //
// func (l List[T comparable]) Max() T { // func (l List[T Ordered]) Max() T {
// if l.Empty() { // if l.Empty() {
// var v T // var v T
// return v // return v

@ -110,6 +110,7 @@ func TestMap(t *testing.T) {
eq(t, 20, nums.At(1)) eq(t, 20, nums.At(1))
eq(t, 30, nums.At(2)) eq(t, 30, nums.At(2))
eq(t, 0, nums.At(3)) eq(t, 0, nums.At(3))
eq(t, 30, Max(nums))
} }
func TestIter(t *testing.T) { func TestIter(t *testing.T) {

Loading…
Cancel
Save