Software Engineering

Tips on how to carry out Operate Iteration in Golang

Tips on how to carry out Operate Iteration in Golang
Written by admin


The problem

The aim of this problem is to jot down a higher-order perform returning a brand new perform that iterates on a specified perform a given variety of occasions. This new perform takes in an argument as a seed to start out the computation.

As an illustration, take into account the perform getDouble. When run twice on worth 3, yields 12 as proven under.

getDouble(3) => 6
getDouble(6) => 12

Allow us to identify the brand new perform createIterator and we should always be capable to receive the identical outcome utilizing createIterator as proven under:

var doubleIterator = createIterator(getDouble, 2); // Runs *getDouble* twice
doubleIterator(3) => 12

For the sake of simplicity, all perform inputs to createIterator would perform returning a small quantity and the variety of iterations would at all times be integers.

The answer in Golang

Possibility 1:

package deal resolution
func CreateIterator(fn func(int) int,n int) func(int) int {
  return func (i int) int {
    for j := 0; j < n; j++ { i = fn(i) }
    return i
  }
}

Possibility 2:

package deal resolution
func CreateIterator(fn func(int) int,n int) func(int) int {
  if n == 0 {
    return func(x int) int { return x } // id
  } else {
    return func(x int) int { return CreateIterator(fn, n-1)(fn(x)) }
  }
}

Possibility 3:

package deal resolution
func CreateIterator(fn func(int) int,n int) func(int) int {
    if n < 1 {
      return nil
    }
    var retFunc = func(r int) int {
      for i := n ; i>0 ; i-- {
        r = fn(r)
      }
      return r
    }
    return retFunc
}

Check instances to validate our resolution

package deal solution_test
import (
    . "github.com/onsi/ginkgo"
    . "github.com/onsi/gomega"
)
var _ = Describe("Iterator for 'getDouble' perform",func() {
    var getDouble = func(n int) int {return 2*n}
    It("Working the iterator as soon as",func() {
        doubleIterator := CreateIterator(getDouble,1)
        Anticipate(doubleIterator(3)).To(Equal(6))
        Anticipate(doubleIterator(5)).To(Equal(10))
    })
    It("Working the iterator twice",func() {
        getQuadruple := CreateIterator(getDouble,2)
        Anticipate(getQuadruple(2)).To(Equal(8))
        Anticipate(getQuadruple(5)).To(Equal(20))
    })
})

About the author

admin

Leave a Comment