Hello guys I am trying to make a simple recursive method that simply takes in an accumulator and a target value. Then add one to the accumulator until it reaches the target value. I am very new to Ocaml but have a decent background in java.
I wrote up a quick snippet of code that shows what I want to do in java:
public static int rec(int acc,int target) {
if (acc == target) {
return 0;
} else {
return rec(acc+1, target);
}
}
here is my attempt to mimic this code in Ocaml:
let h_sequence x =
let rec helper acc x = function
| acc -> x
| _ -> helper acc+1 x
in
helper 0 x;;
however I get the following error:
Error: This expression has type 'a -> 'b -> 'a
but an expression was expected of type int
Here is how I am trying to understand the Ocaml code. So we have a function h_sequence that has a paramater x. Inside of the function h_sequence we have a recursive function named helper which has two paramaters acc and x. If acc = x then return x. Else start the recursion by passing in helper, add one to the acc and then return x. And after the in it is passing the helper function, setting 0 for the acc and setting x as x. Please let me know if my logic is off. Any help will be much appreciated!
edit new code:
let h_sequence x =
let rec helper acc x =
if acc = x then
acc
else
helper (acc+1) x
in
helper 0 x;;
helperactually has three "parameters":acc,x, and another "parameter" that that is matched usingfunction. - Flux