Skip to content

Instantly share code, notes, and snippets.

@TrisDing
Last active August 29, 2015 14:05
Show Gist options
  • Save TrisDing/1804e4115c9648acb43e to your computer and use it in GitHub Desktop.
Save TrisDing/1804e4115c9648acb43e to your computer and use it in GitHub Desktop.
A tour of Go
// 25. Exercise: Loops and Functions
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := float64(1)
y := float64(0)
for {
z = z-(z*z-x)/(2*z)
if math.Abs(z-y) < 1e-15 {
return y
}
y = z
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
}
// 38. Exercise: Slices
package main
import (
"code.google.com/p/go-tour/pic"
)
func Pic(dx, dy int) [][]uint8 {
result := make([][]uint8, dy);
for x := 0; x < dy; x++ {
result[x] = make([]uint8, dx);
for y := 0; y < dx; y++ {
result[x][y] = uint8(x^y);
//result[x][y] = uint8((x+y)/2);
//result[x][y] = uint8(x*y);
}
}
return result;
}
func main() {
pic.Show(Pic)
}
// 43. Exercise: Maps
package main
import (
"strings"
"code.google.com/p/go-tour/wc"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
a := strings.Fields(s)
n := len(a)
for i := 0; i < n; i++ {
(m[a[i]])++
}
return m
}
func main() {
wc.Test(WordCount)
}
// 46. Exercise: Fibonacci closure
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
m := 0
n := 1
return func() int {
m, n = n, m+n
return m
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
// 50. Advanced Exercise: Complex cube roots
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment