Skip to content

Instantly share code, notes, and snippets.

@bifidokk
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save bifidokk/1d5ca94464e94866a05e to your computer and use it in GitHub Desktop.

Select an option

Save bifidokk/1d5ca94464e94866a05e to your computer and use it in GitHub Desktop.
golang tour exercises
/* Exercise: Maps */
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
fields := strings.Fields(s)
m := make(map[string]int)
for i := range(fields){
m[ fields[i] ]++
}
return m
}
func main() {
wc.Test(WordCount)
}
/******************************************************************************************************/
/* Exercise: Fibonacci closure */
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a, b, c := 0, 1, 0
return func() int {
a, b, c = b, (a + b), a
return c
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
/******************************************************************************************************/
/* Exercise: Stringers */
package main
import (
"fmt"
"strings"
"strconv"
)
type IPAddr [4]byte
func (ip IPAddr) String() string {
var ip_array []string
for _, i := range(ip){
ip_array = append(ip_array, strconv.Itoa(int(i)))
}
return strings.Join(ip_array, ".")
}
// TODO: Add a "String() string" method to IPAddr.
func main() {
addrs := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for n, a := range addrs {
fmt.Printf("%v: %v\n", n, a)
}
}
/******************************************************************************************************/
/* Exercise: Errors */
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string{
return fmt.Sprintf("cannot Sqrt negative number: %g", e)
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return x, ErrNegativeSqrt(x)
}
z := float64(2.)
s := float64(0)
for {
z = z - (z*z - x)/(2*z)
if math.Abs(s-z) < 1e-15 {
break
}
s = z
}
return s, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
/******************************************************************************************************/
/* Exercise: Readers */
package main
import "code.google.com/p/go-tour/reader"
type MyReader struct{}
func (e MyReader) Read( b []byte ) (int, error) {
b[0] = 'A'
return 1, nil
}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func main() {
reader.Validate(MyReader{})
}
/******************************************************************************************************/
/* Exercise: rot13Reader */
package main
import (
"io"
"os"
"strings"
"bytes"
)
var ascii_uppercase = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
var ascii_lowercase = []byte("abcdefghijklmnopqrstuvwxyz")
var ascii_uppercase_len = len(ascii_uppercase)
var ascii_lowercase_len = len(ascii_lowercase)
func rot13(b byte) byte {
pos := bytes.IndexByte(ascii_uppercase, b)
if pos != -1 {
return ascii_uppercase[(pos + 13) % ascii_uppercase_len]
}
pos = bytes.IndexByte(ascii_lowercase, b)
if pos != -1 {
return ascii_lowercase[(pos + 13) % ascii_lowercase_len]
}
return b
}
type rot13Reader struct {
r io.Reader
}
func(rot rot13Reader) Read( b []byte ) (int, error) {
n, error := rot.r.Read(b)
for i := 0; i < n; i++ {
b[i] = rot13(b[i])
}
return n, error
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
/******************************************************************************************************/
/* Exercise: HTTP Handlers */
package main
import (
"log"
"net/http"
"fmt"
)
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w, s)
}
func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w, s.Greeting, s.Punct, s.Who)
}
func main() {
// your http.Handle calls here
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
log.Fatal(http.ListenAndServe("localhost:4000", nil))
}
/******************************************************************************************************/
/* Exercise: Images */
package main
import (
"code.google.com/p/go-tour/pic"
"image"
"image/color"
)
type Image struct{
width int
height int
color uint8
}
func (i Image) ColorModel() color.Model {
return color.RGBAModel
}
func (i Image) Bounds() image.Rectangle {
return image.Rect(0, 0, i.width, i.height)
}
func (i Image) At(x, y int) color.Color {
return color.RGBA{i.color, i.color, i.color, 255}
}
func main() {
m := Image{100, 100, 0}
pic.ShowImage(m)
}
/******************************************************************************************************/
/* Exercise: Equivalent Binary Trees */
package main
import (
"code.google.com/p/go-tour/tree"
"fmt"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
walkTree(t, ch)
close(ch)
}
func walkTree(t *tree.Tree, ch chan int) {
if t != nil {
walkTree(t.Left, ch)
ch <- t.Value
walkTree(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := range ch1 {
if i != <- ch2 {
return false
}
}
return true
}
func main() {
ch := make(chan int)
go Walk(tree.New(2), ch)
for v := range ch {
fmt.Print(v)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment