简体   繁体   中英

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.

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

In your case is_base base num/10 is parsed as (is_base base num)/10 , ie, 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 (ie, 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.

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM