Counter Variable in Ocaml?

If you can't use mutable states in Ocaml, How would you go about making a counter variable in a recursive function. For example:

Say you have a data type e you want to pattern match an expression (of that data type) recursively.

Match expression (e: example) : int
|O(i) -> int x + 1

So in that sample (other cases purposely left out), if you find an O(i) you want your int x to increase from 0, + 1 + 2 + 3...

When I try implementing this it says an "unbound value int". So how would you create a variable that can change with each iteration.

Sorry If this doesn't make sense.

1

2 Answers

One way to switch from the imperative to the functional way of looking at things is to imagine that every variable you would want to change is a parameter of a function. When you want to change the value of the variable, you call the function passing the new value.

It might sound crazy (or maybe it doesn't), but that's actually how things work in FP.

Here is some imperative code to count the number of times the number 5 appears in a list of integers:

 let how_many_5s l = let rest = ref l in let count = ref 0 in while !rest <> [] do if List.hd !rest = 5 then count := !count + 1; rest := List.tl !rest done; !count

Here is functional code to do the same thing. The variables that are modified in the above code, the remaining list and the counter, are parameters to the inner function.

 let how_many_5s_functional list = let rec inner count list = match list with | [] -> count | 5 :: t -> inner (count + 1) t | _ :: t -> inner count t in inner 0 list
1

I'm not entirely sure what you're asking, and what syntax you're using (it's not OCaml), but since you mention "recursion" and "counter variable" I'm going to take a stab at illustrating how you increase a counter during recursion using this example, which constructs a list with numbers from a to b inclusive:

let rec range a b = if a > b then [] else a :: range (a + 1) b

For each iteration the value of a will increase by 1 until it reaches b, and the list in constructed by adding a to the head of the list generated by running range recursively with an increasing a.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like