hussain sagar
hussain sagar

Reputation: 61

Applying a function n times

I am trying to apply a function to a value n times.

Currently, I have

let rec n_times (f, n, v) = 
 if n > 0 then
  n_times f n-1 (f v)
 else 
  v

For some reason I keep getting an error that says

This expression has type 'a but an expression was expected of type 'a * int * 'b 
The type variable 'a occurs inside 'a * int * 'b

I saw a few posts that address the same problem I am working on but none of them gets the same error.

Upvotes: 0

Views: 1079

Answers (4)

vog
vog

Reputation: 25597

There seems to be a misunderstanding in how OCaml functions with multiple arguments are defined. You should replace

let rec n_times (f, n, v) =

with:

let rec n_times f n v =

Upvotes: 0

jmb2341
jmb2341

Reputation: 318

There are at least two problems, it would help to know what the purpose is other than recursion.

To get this to run you have to change your third line. n_times is defined with three inputs so it needs to be called with three. Also the function is defined to take a general, integer, and general input and output a general type.

You could remove (f v) and input just v every loop,

# let rec n_times (f, n, v) =
    if n > 0 then
        n_times (f , n-1 , v)
    else
      v;;
val n_times : 'a * int * 'b -> 'b = <fun>
# n_times(2,3,4);;
- : int = 4

This will however always return just v at the end.

You could also replace (f v) with a list and preapped it each loop,

# let rec n_times (f, n, v) =
    if n > 0 then
        n_times (f , n-1 , f::v)
    else
      v;;
val n_times : 'a * int * 'a list -> 'a list = <fun>
# n_times(2,3,[4]);;
- : int list = [2; 2; 2; 4]
# n_times(2,5,[4]);;
- : int list = [2; 2; 2; 2; 2; 4]

This allows the list to grow with each loop.

Upvotes: 0

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

You have defined the function to take a 3-tuple of values. So when you call it recursively you need to supply a 3-tuple:

n_times (f, n - 1, f v)

Upvotes: 0

Et7f3XIV
Et7f3XIV

Reputation: 619

In the first line of your code: you say "I declare a function called n_times that take a triplet (f, n, v) so one argument" then at the call site (third line) you give 3 arguments.

To fix this: write let rec n_times f n v = on line 1 or n_times (f, n-1, (f v)) on line 3.

Upvotes: 2

Related Questions