2018年8月29日水曜日

開発環境

  • macOS High Sierra - Apple (OS)
  • Emacs (Text Editor)
  • Go (プログラミング言語)

Introducing Go: Build Reliable, Scalable Programs (Caleb Doxsey (著)、O'Reilly Media)のChapter 9.(Testing)、Exercises(No. 1866)2.を取り組んでみる。

コード(Emacs)

~/go/src/introducing-go/chapter8/math/math_test.go(GOPATH="~/go")

package math

import "testing"

type testpair struct {
 values []float64
 value  float64
}

var testsAverage = []testpair{
 {[]float64{}, 0},
 {[]float64{1}, 1},
 {[]float64{1, 2}, 1.5},
 {[]float64{1, 2, 3, 4, 5}, 3},
 {[]float64{-1, 1}, 0},
}

func TestAverage(t *testing.T) {
 for _, pair := range testsAverage {
  v := Average(pair.values)
  if v != pair.value {
   t.Error(
    "For", pair.values,
    "expected", pair.value,
    "got", v,
   )
  }
 }
}

var testsMin = []testpair{
 {[]float64{}, 0},
 {[]float64{1}, 1},
 {[]float64{1, 2}, 1},
 {[]float64{5, 1, 4, 2, 3}, 1},
 {[]float64{1, -1, 0}, -1},
}

func TestMin(t *testing.T) {
 for _, pair := range testsMin {
  v := Min(pair.values)
  if v != pair.value {
   t.Error(
    "For", pair.values,
    "expected", pair.value,
    "got", v,
   )
  }
 }
}

var testsMax = []testpair{
 {[]float64{}, 0},
 {[]float64{1}, 1},
 {[]float64{1, 2}, 2},
 {[]float64{1, 5, 2, 4, 3}, 5},
 {[]float64{-1, 1, 0}, 1},
}

func TestMax(t *testing.T) {
 for _, pair := range testsMax {
  v := Max(pair.values)
  if v != pair.value {
   t.Error(
    "For", pair.values,
    "expected", pair.value,
    "got", v,
   )
  }
 }
}

~/go/src/introducing-go/chapter8/math/math.go(GOPATH="~/go")

// Package math provides Min and Max functions that find the minimum and maximum
// values in a slice of float64s
package math

func Average(xs []float64) float64 {
 if len(xs) == 0 {
  return 0
 }
 total := 0.0
 for _, v := range xs {
  total += v
 }
 return total / float64(len(xs))
}

// Finds the minimum values in a slice of float64s
func Min(xs []float64) float64 {
 if len(xs) == 0 {
  return 0
 }
 m := xs[0]
 for _, x := range xs[1:] {
  if x < m {
   m = x
  }
 }
 return m
}

// Finds the maxmum values in a slice of float64s
func Max(xs []float64) float64 {
 if len(xs) == 0 {
  return 0
 }
 m := xs[0]
 for _, x := range xs[1:] {
  if x > m {
   m = x
  }
 }
 return m
}

入出力結果(Terminal)

$ go test
PASS
ok   introducing-go/chapter8/math 0.005s
$ go test -v
=== RUN   TestAverage
--- PASS: TestAverage (0.00s)
=== RUN   TestMin
--- PASS: TestMin (0.00s)
=== RUN   TestMax
--- PASS: TestMax (0.00s)
PASS
ok   introducing-go/chapter8/math 0.005s
$ 

0 コメント:

コメントを投稿