TransWikia.com

Function composition using Go syntax

Stack Overflow Asked by overexchange on July 28, 2020

Below is the problem:

Define a function make_fn_repeater which takes in a one-argument function
f and an integer x. It should return another function which takes in one
argument, another integer. This function returns the result of applying f to
x this number of times.
Make sure to use recursion in your solution, as shown below:


func make_fn_repeater(___________________):
    if _______________________:
          return __________________
    else:
          return __________________
    return ____________________

Sample output:

incr_1 := make_func_repeater(lambda x: x + 1, 1)
incr_1(2) // returns 3
incr_1(5) // returns 6

Below solution is without recursion:

package main

import "fmt"

type fn func(int) int

func makeFnRepeater(f fn, x int) fn {

    return func(y int) int {
        return f(y)
    }

}

func main() {
    inc := makeFnRepeater(func(x int) int { return x + 1 }, 1)
    fmt.Println(inc(2))
    fmt.Println(inc(5))

}

Is it possible to implement solution using recursion? I don’t see that

One Answer

It sounds like you want to do this:

func makeFnRepeater(f fn, x int) fn {
  if x == 1 {
    return f
  } else {
    return func(y int) int {
      return f(makeFnRepeater(f, x - 1)(y))
    }
  }
}

https://play.golang.org/p/YbiSClzipOK

Correct answer by dave on July 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP