I need to count the digits of a number in a recursive way using Standard ML, assuming that the representation of the number 0 has 1 digit.
fun digitCount 0 = 1
| digitCount n = 1 + digitCount (n div 10)
It would be easy to do if countDigit(0)
was 0, but in the code that I wrote the result will always be added by one.
What about using if then else
statement instead of pattern-matching on zero value?
fun digitCount n =
if n < 10
then 1
else 1 + digitCount (n div 10)
It's not much more verbose than pattern-matching a can be even written as one-line:
fun digitCount n = if n < 10 then 1 else 1 + digitCount (n div 10)