2016年2月6日土曜日

開発環境

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

Introducing Go (Caleb Doxsey (著)、O'Reilly Media)のChapter 8.(Packages)、Exercises 1-5.(No. 1811)を取り組んでみる。

Exercises 1-5.(No. 1811)

コード(Emacs)

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

package math

func Average(xs []float64) float64 { 
 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 {
 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 {
 max := xs[0]
 for _, x := range xs[1:] {
  if x > max {
   max = x
  }
 }
 return max
}

main.go

package main

// 2. alias
import f "fmt"
import "golang-book/chapter8/math"

func main() {
 f.Println("Hello, alias World!")
 xs := []float64{1, 2, 3, 4}
 ys := []float64{5, 1, 4, 2, 3, 10, 6, 9, 7, 8}
 avg := math.Average(xs)
 min := math.Min(ys)
 max := math.Max(ys)
 f.Println(ys)
 f.Println("average", avg)
 f.Println("minimum", min)
 f.Println("max", max)
}

入出力結果(Terminal)

$ go run main.go
Hello, alias World!
[5 1 4 2 3 10 6 9 7 8]
average 2.5
minimum 1
max 10
$ godoc golang-book/chapter8/math Max
func Max(xs []float64) float64
    Finds the maximum of a series of numbers


$ godoc golang-book/chapter8/math Min
func Min(xs []float64) float64
    Finds the minnimum of a series of numbers


$ 

0 コメント:

コメントを投稿