package foodchain import ( "bytes" "strings" "text/template" ) const testVersion = 2 const lyrics = `I know an old lady who swallowed a {{.Animal}}. {{- if eq .Animal "spider"}} It wriggled and jiggled and tickled inside her. {{- else if eq .Animal "bird"}} How absurd to swallow a bird! {{- else if eq .Animal "cat"}} Imagine that, to swallow a cat! {{- else if eq .Animal "dog"}} What a hog, to swallow a dog! {{- else if eq .Animal "goat"}} Just opened her throat and swallowed a goat! {{- else if eq .Animal "cow"}} I don't know how she swallowed a cow! {{- end}} {{- range .Animals}} She swallowed the {{.A}} to catch the {{.B}}{{if eq .B "spider"}} that wriggled and jiggled and tickled inside her{{end}}. {{- end}} {{- if eq .Animal "horse"}} She's dead, of course! {{- else}} I don't know why she swallowed the fly. Perhaps she'll die. {{- end}}` var animals = []string{ "fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse", } type pair struct { A, B string } type verse struct { Animal string Animals []pair } var tmpl = template.Must(template.New("song").Parse(lyrics)) func Verse(n int) string { buf := new(bytes.Buffer) pairs := []pair{} if n < len(animals) { for i := 0; i < n-1; i++ { p := pair{A: animals[i+1], B: animals[i]} pairs = append([]pair{p}, pairs...) } } v := verse{ Animal: animals[n-1], Animals: pairs, } tmpl.Execute(buf, v) return buf.String() } func Verses(from, to int) string { buf := make([]string, to-from+1) for i := 0; i < to-from+1; i++ { buf[i] = Verse(i + 1) } return strings.Join(buf, "\n\n") } func Song() string { return Verses(1, 8) }