Skip to content

Instantly share code, notes, and snippets.

@fanzeyi
Created September 27, 2012 15:45
Show Gist options
  • Save fanzeyi/3794725 to your computer and use it in GitHub Desktop.
Save fanzeyi/3794725 to your computer and use it in GitHub Desktop.
My answer for `The Tour of Go`
package main
import "fmt"
import "math/cmplx"
func Cbrt(x complex128) complex128 {
z := x / 4
for i := 0; i < 10; i++ {
z = z - (cmplx.Pow(z, 3) - x) / (3 * z * z)
}
return z
}
func main() {
fmt.Println(Cbrt(2))
}
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
times := 0
x,y := 0,1
return func() int {
if times == 0 {
times++
return 0
}else if times == 1 {
times++
return 1
}
tmp := y
y = x + y
x = tmp
return y
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
package main
import "strings"
import "tour/wc"
func WordCount(s string) map[string]int {
m := map[string]int{}
for _,word := range strings.Fields(s) {
m[word] = m[word] + 1
}
return m
}
func main() {
wc.Test(WordCount)
}
package main
import "tour/pic"
func Pic(dx, dy int) [][]uint8 {
p := make([][]uint8, dy)
for i := range p {
p[i] = make([]uint8, dx)
}
return p
}
func main() {
pic.Show(Pic)
}
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := x / 2
for i := 0; i < 10; i++ {
z = z - (z * z - x) / (2 * z)
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment