Skip to content

Instantly share code, notes, and snippets.

@takashima0411
Created March 6, 2020 18:59
Show Gist options
  • Save takashima0411/f30b24751313bffa8cc0398fa964512d to your computer and use it in GitHub Desktop.
Save takashima0411/f30b24751313bffa8cc0398fa964512d to your computer and use it in GitHub Desktop.
fold left on go
package main
import (
"./money"
"fmt"
)
func main() {
mon := make([]money.Money, 0, 10)
mon = append(mon, money.NewSen())
mon = append(mon, money.NewGosen())
mon = append(mon, money.NewSen())
mon = append(mon, money.NewSen())
mon = append(mon, money.NewSen())
mon = append(mon, money.NewSen())
sum := foldl(mon, money.NewZero(), func(m1 money.Money, m2 money.Money) money.Money {
result := m1.Add(m2)
return result
})
fmt.Print("sum: ", sum.Price())
}
func foldl(ls []money.Money, z money.Money, op func(money.Money, money.Money) money.Money) money.Money {
if len(ls) == 0 {
return z
} else {
return foldl(ls[1:], op(z, ls[0]), op)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment