/*
Package listops provides methods for handling IntList type.
*/
package listops
// IntList is a list of integers
type IntList []int
type binFunc func(int, int) int
type predFunc func(int) bool
type unaryFunc func(int) int
// Foldl folds the list from left
func (base IntList) Foldl(fn binFunc, init int) (acc int) {
acc = init
for i := 0; i < base.Length(); i++ {
acc = fn(acc, base[i])
}
return
}
// Foldr folds the list from right
func (base IntList) Foldr(fn binFunc, init int) (acc int) {
acc = init
for i := base.Length() - 1; i >= 0; i-- {
acc = fn(base[i], acc)
}
return
}
// Reverse reverses the list called on
func (base IntList) Reverse() IntList {
res := make(IntList, base.Length())
for i := 0; i < base.Length(); i++ {
res[i] = base[base.Length()-i-1]
}
return res
}
// Map runs the function on every element of the list
func (base IntList) Map(fn unaryFunc) IntList {
for i := 0; i < base.Length(); i++ {
base[i] = fn(base[i])
}
return base
}
// Length reports the length of the list
func (base IntList) Length() int {
return len(base)
}
// Filter reduces the list elements to those where calling fn results true
func (base IntList) Filter(fn predFunc) IntList {
res := IntList{}
for i := 0; i < base.Length(); i++ {
if fn(base[i]) == true {
res = append(res, base[i])
}
}
return res
}
// Concat appends other lists to the base one
func (base IntList) Concat(lists []IntList) IntList {
for i := 0; i < len(lists); i++ {
base = base.Append(lists[i])
}
return base
}
// Append appends a list to the base one
func (base IntList) Append(add IntList) IntList {
sum := make(IntList, base.Length()+add.Length())
for i := 0; i < base.Length(); i++ {
sum[i] = base[i]
}
for j := 0; j < len(add); j++ {
sum[base.Length()+j] = add[j]
}
return sum
}