Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
sum.go51 linesDownload Raw Back to typeparam
1// run2 3// Copyright 2021 The Go Authors. All rights reserved.4// Use of this source code is governed by a BSD-style5// license that can be found in the LICENSE file.6 7package main8 9import (10	"fmt"11)12 13func Sum[T interface{ int | float64 }](vec []T) T {14	var sum T15	for _, elt := range vec {16		sum = sum + elt17	}18	return sum19}20 21func Abs(f float64) float64 {22	if f < 0.0 {23		return -f24	}25	return f26}27 28func main() {29	vec1 := []int{3, 4}30	vec2 := []float64{5.8, 9.6}31	got := Sum[int](vec1)32	want := vec1[0] + vec1[1]33	if got != want {34		panic(fmt.Sprintf("got %d, want %d", got, want))35	}36	got = Sum(vec1)37	if want != got {38		panic(fmt.Sprintf("got %d, want %d", got, want))39	}40 41	fwant := vec2[0] + vec2[1]42	fgot := Sum[float64](vec2)43	if Abs(fgot-fwant) > 1e-10 {44		panic(fmt.Sprintf("got %f, want %f", fgot, fwant))45	}46	fgot = Sum(vec2)47	if Abs(fgot-fwant) > 1e-10 {48		panic(fmt.Sprintf("got %f, want %f", fgot, fwant))49	}50}51 
codekingpro/portable-devtools · Team Ai