Skip to content

Instantly share code, notes, and snippets.

@gocs
Created May 1, 2020 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gocs/d15ad45bd623829bd116ccd58f2b4a2c to your computer and use it in GitHub Desktop.
Save gocs/d15ad45bd623829bd116ccd58f2b4a2c to your computer and use it in GitHub Desktop.
go contracts proposal thingy
// Copyright 2020 github.com/gocs
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"log"
"errors"
)
type T {
int
int64
float32
float64
}
type List T struct {
head *node T
len int
Each func() (T, error)
}
func NewList() *List T {
l := &(List T){}
l.Each = enumerator(l)
return l
}
func enumerator(t *List T) func()(T, error) {
curr := t.head
return func()(T, error) {
if curr == nil {
var zero T
return zero, errors.New("end of list; nil head")
}
data := curr.data
curr = curr.next
return data, nil
}
}
func (t List T) Add(input T) {
n := newnode(input)
n.next = t.head
t.head = n
t.len++
}
func (t List T) Sub(index int) T {
i := 0
var data T
var prev *node T
for curr := t.head; curr != nil; curr = prev.next {
if i != index {
i++
prev = curr
continue
}
if prev == nil {
t.head = curr.next
} else {
prev.next = curr.next
}
data = curr.data
t.len--
}
return data
}
func (t List T) Max() T {
max := 0
for curr := t.head; curr != nil; curr = curr.next {
if max < curr.data {
max = curr.data
}
}
return max
}
func (t List T) Len() int {return t.len}
type node T struct {
next *node T
data T
}
func newnode(t T) *node {
return &node{data: t}
}
func main() {
list := (List float64){333.1}
list.Add(333.5)
list.Add(333.4)
log.Println("Len:", list.Len()) // Len: 3
log.Println("Max:", list.Max().(int)) // Max: 333
log.Println("Max:", list.Max().(float32)) // Max: 333.5
for v, err := list.Each(); err != nil; v, err = list.Each() {
log.Println("v:", v.(int))
}
// v: 333
// v: 333
// v: 333
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment