Skip to content

Instantly share code, notes, and snippets.

@usirin
Last active August 29, 2015 14:01
Show Gist options
  • Save usirin/1504c8dd1f69ecd87689 to your computer and use it in GitHub Desktop.
Save usirin/1504c8dd1f69ecd87689 to your computer and use it in GitHub Desktop.
gotour
package main
import (
"fmt"
"math/cmplx"
)
func Cbrt(x complex128) complex128 {
z := complex128(2)
s := complex128(0)
for {
z = z - (cmplx.Pow(z,3) - x)/(3 * (z * z))
if cmplx.Abs(s-z) < 1e-17 {
break
}
s = z
}
return z
}
func main() {
fmt.Println(Cbrt(8))
}
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))
}
func Sqrt(f float64) (float64, error) {
if f < 0 {
return float64(0), ErrNegativeSqrt(f)
}
return math.Sqrt(f), nil
}
func main() {
fmt.Println(Sqrt(4))
fmt.Println(Sqrt(-2))
}
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a := 0
b := 1
return func() int {
a, b = b, a + b
return a
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
for _, word := range strings.Fields(s) {
m[word] += 1
}
return m
}
func main() {
wc.Test(WordCount)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment