W.W
W.W

Reputation: 27

Ocaml - Check if every digit of a given int is less than "base" recursively

Check if every digit of a given int is less than "base" in a recursive manner.

In "pseudo-code"

 boolean is_base ( int base, int num)
{
    if num = 0
        return true;
    else if num mod 10 < base 
        is_base (base, num/10)
    else return false
}

Ocaml code

let rec is_base base num= 
    if num = 0 then 1
    else if num mod 10 < base then is_base base num/10
    else 0

Is a looping recursion.

Upvotes: 0

Views: 253

Answers (2)

ivg
ivg

Reputation: 35210

The function application operator (that's in OCaml is just a juxtaposition of a function and its arguments, e.g., f x) has higher precedence than arithmetic operators (i.e., it binds tighter), so the f x/10 expression is treated by OCaml as (f x) / 10.

In your case is_base base num/10 is parsed as (is_base base num)/10, i.e., first a recursive call is made with base and num parameters, then the result is divided by 10. Since your recursive call is always made with the same parameter, it never terminates.

Also, if you would use bool for representing booleans (i.e., true and false) compiler will tell you that your code is incorrect. Always use the most concrete type, this will help the compiler to provide better diagnostics.

Upvotes: 2

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66803

(Your code is a bit of a moving target....)

There's no need to change num in the code you show. You can pass num / 10 without changing num.

In general this is how to write functional code. What you would normally consider to be a mutable value becomes a function parameter instead.

Upvotes: 0

Related Questions