Question: I'm sure there's a way to do this elegantly in SML but I'm having difficulty keeping track of the number of iterations (basically the number of times my function has been called).

I'm trying to write a function that evaluates to a pair of numbers, one for the floor of the answer and the other for the remainder. So if you called:

`divmod(11, 2)`, you'd get `(5, 1)` back.

Here's what I have so far:

```
divmod(number : int, divisor : int) =
    if number < divisor then
        (number, count)
    else
        divmod(number - divisor, divisor);

```

Obviously, I haven't set up my count variable so it won't compile but that's the idea of the algorithm. All that's left is initializing count to 0 and being able to pass it between recursive calls. But I'm only allowed the two parameters for this function.

I can, however, write auxiliary functions. 

Thoughts?

Answer: 
If SML has support for nested functions you could do like this:

```
divmod(number : int, divisor : int) =
   _divmod(n : int, d : int, count : int) = 
      if n < d then
         (count, n)
      else
         _divmod(n - d, d, count + 1)
   _divmod(number, divisor, 0)

```
Personally, I *like* the fact that SML isn't a pure functional language. Keeping track of function calls is naturally done via side effects (rather than explicitly passing a counter variable).

For example, given a generic recursive Fibonacci:

```
fun fib 0 = 0
|   fib 1 = 0
|   fib n = fib(n-2) + fib(n-1);

```

You can modify it so that every time it is called it increments a counter as a side effect: 

```
counter = ref 0;

fun fib 0 = (counter := !counter + 1; 0)
|   fib 1 = (counter := !counter + 1; 1)
|   fib n = (counter := !counter + 1; fib(n-2) + fib(n-1));

```

You can use this directly or wrap it up a bit:

```
fun fibonacci n = (
    counter :=0; 
    let val v = fib n 
    in 
        (!counter,v) 
    end);

```

With a typical run:

```
- fibonacci 30;
val it = (2692537,832040) : int * int  

```

(Which, by the way, shows why this version of the Fibonacci recursion isn't very good!)