Created
December 14, 2015 05:51
-
-
Save vanphuong12a2/72d05a18e175abe0db32 to your computer and use it in GitHub Desktop.
A Tour of Go
This file contains hidden or 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
//Cbrt.go | |
//Advanced Exercise: Complex cube roots | |
package main | |
import ( | |
"fmt" | |
"math/cmplx" | |
) | |
func Cbrt(x complex128) complex128 { | |
var z complex128 = 1 | |
for i:= 1; i < 10; i++ { | |
delta := (cmplx.Pow(z,3) - x)/(3 * cmplx.Pow(z,2)) | |
z = z - delta | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Cbrt(2)) | |
} | |
//Exercise: Errors | |
package main | |
import ( | |
"fmt" | |
) | |
type ErrNegativeSqrt float64 | |
func (e ErrNegativeSqrt) Error() string{ | |
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e)) | |
} | |
func Sqrt(f float64) (float64, error) { | |
if f < 0 { | |
return 0, ErrNegativeSqrt(f) | |
} | |
var z float64 = 1 | |
var delta float64 | |
for { | |
delta = (z*z - f)/(2*z) | |
z = z - delta | |
if delta*delta < 0.00001 { | |
return z, nil | |
} | |
} | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(Sqrt(-2)) | |
} | |
//Exercise: Fibonacci closure | |
package main | |
import "fmt" | |
// fibonacci is a function that returns | |
// a function that returns an int. | |
func fibonacci() func() int { | |
var r1, r2 int | |
return func() int { | |
r1, r2 = r2, r1+r2 | |
if r2 == 0{ | |
r2 = 1 | |
} | |
return r1 | |
} | |
} | |
func main() { | |
f := fibonacci() | |
for i := 0; i < 10; i++ { | |
fmt.Println(f()) | |
} | |
} | |
//Exercise: Slices | |
package main | |
import "code.google.com/p/go-tour/pic" | |
func Pic(dx, dy int) [][]uint8 { | |
var img [][]uint8 = make([][]uint8, dx) | |
for x:=0; x < dx; x++{ | |
img[x] = make([]uint8,dy) | |
for y:=0; y<dy; y++{ | |
img[x][y] = uint8(x^y) | |
} | |
} | |
return img | |
} | |
func main() { | |
pic.Show(Pic) | |
} | |
//Exercise: Loops and Functions | |
package main | |
import ( | |
"fmt" | |
) | |
func Sqrt(x float64) float64 { | |
var z float64 = 1 | |
var delta float64 | |
for { | |
delta = (z*z - x)/(2*z) | |
z = z - delta | |
if delta*delta < 0.00001 { | |
return z | |
} | |
} | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
} | |
//Exercise: Maps | |
package main | |
import ( | |
"code.google.com/p/go-tour/wc" | |
"strings" | |
) | |
func WordCount(s string) map[string]int { | |
m := make(map[string]int) | |
for _,w := range strings.Fields(s) { | |
m[w]++ | |
} | |
return m | |
} | |
func main() { | |
wc.Test(WordCount) | |
} | |
//For fibonacci: | |
//Is it a little bit better? | |
func fibonacci() func() int { | |
r1, r2 := 1, 0 | |
return func() int { | |
r1, r2 = r2, r1 + r2 | |
return r1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment