6
$\begingroup$

When writing recursive code that computes the least value at which a condition is true and various other scenarios it is often necessary to specify a base case. What I have done to supply this is create a function parameter that must always have the specified base case passed into it:

least2nbigger[x_, n_] := If[2^n >= x, 2^n, least2nbigger[x, 1 + n]]

This is used with a structure like

least2nbigger[4097, 1]

Where the 1 is the start value for the recursion. x is the only parameter of interest to someone using the function; n is always to be passed as 1.

In SML I would do something like this:

fun least2nbigger x = least2nbigger (x, 1)
|   least2nbigger (x, n) =
let
    p = pow (2, n)
in
    if p > x then p 
    else least2nbigger (x, n+1)    
end;

(My SML is a bit rusty, that might not be entirely valid but the idea is clear).

There is an alternative definition provided for the recursive case; the function can be called without the tuple.

The only way I see to do this in Mathematica would be to make two functions, the recursive case and a dummy function that calls the recursive case with is base parameter. Is there a better way to accomplish this?

$\endgroup$
  • 2
    $\begingroup$ least2nbigger[x_, n_:1] :=... ? $\endgroup$ – Rojo Feb 4 '14 at 3:20
8
$\begingroup$

As Rojo notes in a comment you can make n an Optional parameter with a default value:

f[x_, n_: 1] := If[2^n >= x, 2^n, f[x, 1 + n]]

f[4097]
8192

More manually you could use a definition for the single parameter case:

g[x_] := g[x, 1];
g[x_, n_] := If[2^n >= x, 2^n, g[x, 1 + n]]

g[4097]
8192

You can also convert the If statement into a Condition, e.g.:

h[x_] := h[x, 1];
h[x_, n_] /; 2^n >= x := 2^n
h[x_, n_] := h[x, 1 + n]

h[4097]
8192

You may find that this syntax is somewhat more efficient than If, Switch, etc.

$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.