Worice
Worice

Reputation: 4037

Recursion with two results

I have built a function that recursively calculate the progressive powers of two, up to a certain value n.

let rec aux_pow =
fun e n -> 
    match n with
    | n         ->  1        # I tried with e, but clearly it modifies the result
    | _         ->  2 * aux_pow (e + 1) n

The function will return an integer (2, 4, 8, 16 ... n), that can be used by other functions as parameter etc... . Easy. What I am looking for, is a way to return also the value of e, that is, the grade of the power. Is it actually possible? I know that each function can return only a value. What is the best way to get both the result of the recursion and, in this case, the number of recursion cycles?

I.e. for aux_pow 0 8 how can I have the value of e that is equal to 3 and at the same time making the function return the result of 2 * 2 * 2 = 8? Is it possible? Is it a meaningless problem?

Upvotes: 0

Views: 162

Answers (1)

Eric Olsson
Eric Olsson

Reputation: 4913

The simplest way to return 2 values from a function is to use tuples. I took some liberties with the sample code you provided and came up with a version that should do what you're looking for.

let aux_pow limit =
  let rec aux_pow' value counter =
    match value with
    | n when n = limit -> (limit, counter)
    | n when n > limit -> (int (2. ** double (counter - 1)), counter - 1)
    | _ -> aux_pow' (2 * value) (counter + 1)

  aux_pow' 1 0

It defines an internal recursive function that keeps count of the number of times it is run. The output is a tuple with the value and the count.

It also contains a case when a non-power-of-2 value is specified for the limit.

Upvotes: 3

Related Questions