2016年2月7日日曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Go (version go1.5.3 darwin/amd64) (プログラミング言語)

Introducing Go (Caleb Doxsey (著)、O'Reilly Media)のChapter 9.(Testing)、Exercises 1-2.(No. 1879)を取り組んでみる。

Exercises 1-2.(No. 1879)

コード(Emacs)

~/.go/src/golang-book/chapter8/math/math.go

package math

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

// Finds the minnimum of a series of numbers
func Min(xs []float64) float64 {
 if len(xs) == 0 {
  return 0
 }
 min := xs[0]
 for _, x := range xs[1:] {
  if x < min {
   min = x
  }
 }
 return min;
}

// Finds the maximum of a series of numbers
func Max(xs []float64) float64 {
 if len(xs) == 0 {
  return 0
 }
 max := xs[0]
 for _, x := range xs[1:] {
  if x > max {
   max = x
  }
 }
 return max
}

~/.go/src/golang-book/chapter8/math/math_test.go

package math

import "testing"

type testpair struct {
 values []float64
 result float64
}
func error(t *testing.T, value float64, pair testpair) {
 if value != pair.result {
  t.Error(
   "For", pair.values,
   "expected", pair.result,
   "got", value,
  )
 }
}

var tests_average = []testpair{
 testpair{ values:[]float64{1, 2}, result:1.5 },
 {values:[]float64{1, 1, 1, 1, 1, 1}, result:1 },
 {[]float64{-1, 1}, 0},
 {[]float64{}, 0},
}

func TestAverage(t *testing.T) {
 for _, pair := range tests_average {
  v := Average(pair.values)
  error(t, v, pair)
 }
}

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

func TestMin(t *testing.T) {
 for _, pair := range tests_min {
  v := Min(pair.values)
  error(t, v, pair)
 }
}

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

func TestMax(t *testing.T) {
 for _, pair := range tests_max {
  v := Max(pair.values)
  error(t, v, pair)
 }
}

入出力結果(Terminal)

$ go test
PASS
ok   golang-book/chapter8/math 0.025s
$

0 コメント:

コメントを投稿