2016年2月4日木曜日

開発環境

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

Introducing Go (Caleb Doxsey (著)、O'Reilly Media)のChapter 6.(Functions)、Exercises 1-11.(No. 1096)を取り組んでみる。

Exercises 1-11.(No. 1096)

コード(Emacs)

package main

import "fmt"

func sum(numbers []float64) float64 {
 total := 0.0
 for _, value := range numbers {
  total += value
 }
 return total
}
func halves(n int) (float64, bool) {
 return float64(n) / 2.0, n % 2 == 0
}
func greatestNumber(numbers ...float64) float64{
 result := numbers[0]
 for _, value := range numbers {
  if value > result {
   result = value
  }
 }
 return result
}
func makeOddGenerator() func() uint {
 i := uint(1)
 return func() (ret uint) {
  ret = i
  i += 2
  return 
 }
}
func fib(n uint) uint {
 if n <= 1 {
  return n
 }
 return fib(n - 2) + fib(n - 1)
}
func deferPanicRecover() {
 defer func () {
  str := recover()
  fmt.Println(str)
 }()
 panic("Panic!")
}
func square (x *float64) {
 *x = *x * *x
}
func swap1(x *int, y *int) {
 t := *x
 *x = *y
 *y = t
}
func swap2(x *int, y *int) {
 *x += *y
 *y = *x - *y
 *x = *x - *y
}

func main() {
 fmt.Println("1.")
 numbers := []float64{1,2,3,4,5,6,7,8,9,10}
 fmt.Println(sum(numbers))

 fmt.Println("2.")
 for i := 1; i <= 10; i++ {
  a, b := halves(i)
  fmt.Println(i, ":",  a, b)
 }

 fmt.Println("3.")
 fmt.Println(greatestNumber(5, 1, 4, 2, 3))
 fmt.Println(greatestNumber(1, 2, 3, 4, 5))
 fmt.Println(greatestNumber(1, 2, 5, 3, 4))
 fmt.Println(greatestNumber(4, 3, 5, 2, 1))
 fmt.Println(greatestNumber(5, 5, 5, 5, 5))

 fmt.Println("4.")
 nextOdd := makeOddGenerator()
 fmt.Println(nextOdd())
 fmt.Println(nextOdd())
 fmt.Println(nextOdd())

 fmt.Println("5.")
 fmt.Println(fib(10))
 fmt.Println(fib(20))

 fmt.Println("6.")
 deferPanicRecover()

 fmt.Println("7.")
 x := 10
 fmt.Println(&x)

 fmt.Println("8, 9.")
 xPtr := new(int)
 *xPtr = x
 fmt.Println(xPtr, x)

 fmt.Println("10.")
 y := 1.5
 square(&y) 
 fmt.Println(y == 2.25)

 fmt.Println("11.")
 a := 1
 b := 2
 swap1(&a, &b)
 fmt.Println(a, b)
 c := 3
 d := 4
 swap2(&c, &d)
 fmt.Println(c, d)
}

入出力結果(Terminal)

$ go run main.go
1.
55
2.
1 : 0.5 false
2 : 1 true
3 : 1.5 false
4 : 2 true
5 : 2.5 false
6 : 3 true
7 : 3.5 false
8 : 4 true
9 : 4.5 false
10 : 5 true
3.
5
5
5
5
5
4.
1
3
5
5.
55
6765
6.
Panic!
7.
0xc820062470
8, 9.
0xc820062490 10
10.
true
11.
2 1
4 3
$

0 コメント:

コメントを投稿

Comments on Google+: