如何在SML中递归地计算数字的位数
How to count the digits of a number recursively in SML
我需要使用标准 ML 以递归方式计算数字的位数,假设数字 0 的表示有 1 个数字。
fun digitCount 0 = 1
| digitCount n = 1 + digitCount (n div 10)
如果countDigit(0)
是0就好办了,但是我写的代码里结果总是加1。
使用 if then else
语句而不是对零值进行模式匹配怎么样?
fun digitCount n =
if n < 10
then 1
else 1 + digitCount (n div 10)
它并不比模式匹配更冗长 a 甚至可以写成一行:
fun digitCount n = if n < 10 then 1 else 1 + digitCount (n div 10)
我需要使用标准 ML 以递归方式计算数字的位数,假设数字 0 的表示有 1 个数字。
fun digitCount 0 = 1
| digitCount n = 1 + digitCount (n div 10)
如果countDigit(0)
是0就好办了,但是我写的代码里结果总是加1。
使用 if then else
语句而不是对零值进行模式匹配怎么样?
fun digitCount n =
if n < 10
then 1
else 1 + digitCount (n div 10)
它并不比模式匹配更冗长 a 甚至可以写成一行:
fun digitCount n = if n < 10 then 1 else 1 + digitCount (n div 10)