github.com/l3x/learn-fp-go@v0.0.0-20171228022418-7639825d0b71/4-purely-functional/ch09-functor-monoid/11_monoid/src/monoid/lineitem_monoid.go (about)

     1  package monoid
     2  
     3  type LineitemMonoid interface {
     4  	Zero() []int
     5  	Append(i ...int) LineitemMonoid
     6  	Reduce() int
     7  }
     8  
     9  func WrapLineitem(lineitems []Lineitem) lineitemContainer {
    10  	return lineitemContainer{lineitems: lineitems}
    11  }
    12  
    13  type Lineitem struct {
    14  	Quantity 	int
    15  	Price		int
    16  	ListPrice 	int
    17  }
    18  
    19  
    20  type lineitemContainer struct {
    21  	lineitems []Lineitem
    22  }
    23  
    24  func (lineitemContainer) Zero() []Lineitem {
    25  	return nil
    26  }
    27  
    28  func (i lineitemContainer) Append(lineitems ...Lineitem) lineitemContainer {
    29  	i.lineitems = append(i.lineitems, lineitems...)
    30  	return i
    31  }
    32  
    33  func (i lineitemContainer) Reduce() Lineitem {
    34  	totalQuantity := 0
    35  	totalPrice := 0
    36  	totalListPrice := 0
    37  	for _, item := range i.lineitems {
    38  		totalQuantity += item.Quantity
    39  		totalPrice += item.Price
    40  		totalListPrice += item.ListPrice
    41  	}
    42  	return Lineitem{totalQuantity, totalPrice, totalListPrice}
    43  }
    44