1
votes

I am trying to write a function in SML that takes an integer and outputs the number of digits int he number. For example, user inputs 122, I want to output 3. I thought this functions would do the trick but I am getting some errors in regards to result constraints of clauses not agreeing. And right-hand-side doesn't agree and operator and operand don't agree. I am very new to ML and I do not know what I am doing wrong! Thanks in advance.

fun num_digits nil = nil
| num_digits 0 = 1
| num_digits n = 
    let 
        val x = 1
        fun f(z, a) =
            let
                val c = z+1
                val m = a div 10
            in
                if m >= 1
                then
                    f(c, m)
                else z
            end;
    in
        f(x, n)
    end;
3

3 Answers

1
votes

nil is [] (an empty list).

If you define a function like:

fun f nil = nil
| f x = 3;

That causes syntax error, since int and list are mixed up.

However the following examples are fine, since types matched perfectly:

fun f nil = 2
|f x = 3;

Or

fun f nil = nil
| f x = [3];
2
votes

If there are math functions available and it is positive integers we are talking about, this would do the trick:

digits = floor(log10(number))+1

Zero would have to be handled separately.

0
votes

This resolved the entire problem

fun num_digits 0 = 1 | num_digits n =

Removing num_digits nil = nil fixed it. Not sure why this was causing the issue... maybe because passing in an int and receiving nil is not a valid thing?