Created
September 27, 2012 15:45
-
-
Save fanzeyi/3794725 to your computer and use it in GitHub Desktop.
My answer for `The Tour of Go`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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