[英]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. 以递归的方式检查给定int的每个数字是否小于“基数”。
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
. 函数应用程序运算符(在OCaml中只是一个函数的并置,并且其参数,例如fx
)比算术运算符(即,绑定更紧密)具有更高的优先级,因此fx/10
表达式被OCaml视为(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
. 在您的情况下, is_base base num/10
被解析为(is_base base num)/10
,即,首先使用base
和num
参数进行递归调用,然后将结果除以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. 另外,如果您使用bool
表示布尔值(即true
和false
),则编译器会告诉您您的代码不正确。 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. 无需在显示的代码中更改num
。 You can pass num / 10
without changing num
. 您可以通过num / 10
而不更改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. 您通常认为是可变值的内容将变为函数参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.