2
\$\begingroup\$

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)
}
\$\endgroup\$
4
\$\begingroup\$

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
}
\$\endgroup\$
1
\$\begingroup\$

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)
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.