My quick searching did not reveal anyone sharing their solution to this exercise, so am not sure if there are other (and better) approaches to mine:
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
foo := strings.Fields(s)
m := make(map[string]int)
for i := 0; i < len(foo); i++ {
v, ok := m[foo[i]]
if ok {
m[foo[i]] = v + 1
}
m[foo[i]] = v + 1
}
return m
}
func main() {
wc.Test(WordCount)
}
2 Answers 2
You can be more concise and readable using range
and the fact that the default value of the int is 0
:
func WordCount(s string) map[string]int {
m := make(map[string]int)
for _, w := range(strings.Fields(s)) {
m[w]++
}
return m
}
Programmers spend almost all their time reading code; code should be documented. API users need good documentation too.
A meaningless name like foo
is the first red flag; good names are an excellent form of code documentation.
Go has a documentation tool: Godoc: documenting Go code. "Documentation is a huge part of making software accessible and maintainable."
Here's my solution:
// A Tour of Go. Exercise 40: Maps.
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
// WordCount returns a map of the counts of each "word" in the string s.
func WordCount(s string) map[string]int {
counts := make(map[string]int)
for _, word := range strings.Fields(s) {
counts[word]++
}
return counts
}
func main() {
wc.Test(WordCount)
}