Skip to content

Instantly share code, notes, and snippets.

@tiagopog
Last active March 16, 2017 01:21
Show Gist options
  • Save tiagopog/b9c161b9d172b91f5adc92e6878d681a to your computer and use it in GitHub Desktop.
Save tiagopog/b9c161b9d172b91f5adc92e6878d681a to your computer and use it in GitHub Desktop.
Go - Learning
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
z := 1.0
var prop float64
for prop < 0.9990 || prop > 1.0 {
prev_z := z
z = z - (z * z - x) / (2 * z)
prop = z / prev_z
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := 1.0
var prop float64
for prop < 0.9990 || prop > 1.0 {
prev_z := z
z = z - (z * z - x) / (2 * z)
prop = z / prev_z
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i <= 10; i++ {
z = z - (z * z - x) / (2 * z)
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}
package main
import "fmt"
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
result := make([][]uint8, dy)
for x := range result {
result[x] = make([]uint8, dy)
for y := range result[x] {
result[x][y] = uint8((x+y)/2)
}
}
fmt.Println(result)
return result
}
func main() {
pic.Show(Pic)
}
package main
import "fmt"
func main() {
a := make([]int, 5)
printSlice("a", a) // a len=5 cap=5 [0 0 0 0 0]
b := make([]int, 0, 5) // b len=0 cap=5 []
printSlice("b", b)
c := b[:2] // c len=2 cap=5 [0 0]
printSlice("c", c)
d := c[2:5] // d len=3 cap=3 [0 0 0]
printSlice("d", d)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
package main
import (
"golang.org/x/tour/wc"
"strings"
// "fmt"
)
func WordCount(s string) map[string]int {
result := map[string]int{}
words := strings.Fields(s)
for _, word := range words {
count := 0
for _, comp_word := range words {
if word == comp_word { count++ }
}
result[word] = count
}
return result
}
func main() {
wc.Test(WordCount)
}
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0] // []
printSlice(s)
// Extend its length.
s = s[:4] // [2 3 5 7]
printSlice(s)
// Drop its first two values.
s = s[2:] // [5 7]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
package main
import "fmt"
func main() {
q := []int{2, 3, 5, 7, 11, 13}
fmt.Println(q)
r := []bool{true, false, true, true, false, true}
fmt.Println(r)
s := []struct {
i int
b bool
}{
{2, true},
{3, false},
{5, true},
{7, true},
{11, false},
{13, true},
}
fmt.Println(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment