133k views
3 votes
Write a higher-order function ncall that takes three parameters: n,f,x; it returns x when n=0, returns f(x) when n=1, returns f(f(x)) when n=2, etc. That is, it returns the result of calling f on x, for n times. For instance, invoking ncall with n=4, a function that adds 1 , and x=2 should return 6 . Another example in scheme: a call to (ncall 4 (lambda (x) (+ x 2)) 2) should return 10. In this case f(x)=x+2 (the lambda function) thus for x=2 we are calling f4 times on x i.e. f(f(f(f(x))))=f(f(f(f(2))))=f(f(f(4)))=f(f(6)))=f(8)=10

1 Answer

4 votes

Final answer:

A higher-order function ncall takes three parameters: n, f, and x. It returns x when n is 0, f(x) when n is 1, f(f(x)) when n is 2, and so on. It applies the function f to x for n times.

Step-by-step explanation:

A higher-order function is a function that takes one or more functions as parameters or returns a function as its result. In this case, the higher-order function ncall takes three parameters: n, f, and x. It returns x when n is equal to 0, f(x) when n is equal to 1, f(f(x)) when n is equal to 2, and so on. The function f is applied to x for n times.

For example, if n=4, f is a function that adds 1, and x=2, then invoking ncall would return 6. This is because f(f(f(f(x)))) would be f(f(f(3))), which equals 6.

In Scheme, a call to (ncall 4 (lambda (x) (+ x 2)) 2) would return 10. Here, f(x) is represented by the lambda function that adds 2. So, calling f four times on x (i.e., f(f(f(f(2))))) would give us 10.

User Alex Dunlop
by
7.8k points

No related questions found