0

I want to code a typescript function that repeats a function n times to an argument, in a functional way. Recursion seems to me as a good suggestion.

My attempt in vanilla ES is below.

const repeat = f => times => arg => {
  if(times <= 0) {
    return arg;
  } else {
    const val = repeat(f)(times-1)(f(arg))
    return val;
  }
}

My best attempt in annontating the type does not pass compilation.

const repeat = <T>(f: T=>T) => (times: number) => (arg: T) => {
  if(times <= 0) {
    return arg;
  } else {
    const val: T = repeat(f)(times-1)(f(arg))
    return val;
  }
}

EDIT Following the advice of @arpl, but not writing a separate Interface, I settled for below. The separate definition of "ret" is to allow proper inference of return type.

const repeat = <T>(f: (a: T)=>T) => (t: number) => (a: T) => {
  const ret: T = t > 0 ? repeat(f)(t - 1)(f(a)) : a;
  return ret;
};

1 Answer 1

5

Here is one way that uses an interface.

interface Repeat {
  <T>(f: (a: T) => T): (t: number) => (a: T) => T;
}

const repeat: Repeat = f => t => a => {
  return t > 0 ? repeat(f)(t - 1)(f(a)) : a;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.