1
votes

I'm trying to create a function that will sum the digits of an integer in SML but I'm getting the following error.

Error: operator and operand don't agree [overload conflict]
  operator domain: real * real
  operand:         [* ty] * [* ty]
  in expression:
    n / (d * 10)

I've tried to typecast the variables to real but it didn't work. Also I don't understand why I'm getting this error. Is not possible to use operators such as * and / with int and real in SML?

The code is the following:

fun sumDigits (n) = 
  if n < 10 then n
  else
    let
       val d = 10
     in
       n mod d + sumDigits(trunc(n/(d*10)))
     end
1

1 Answers

2
votes

Looks like you have a few things wrong. To start, you'll want to use "div" rather than "/" when dividing integers. / is for reals. Also, trunc is a function for reals. 3rd, you'll want your recursive logic to just be sumDigits(n div 10), not sumDigits(n div (d*10)). You can also clean up the code by removing the d variable.

fun sumDigits (n) = 
  if n < 10 then n
  else
    n mod 10 + sumDigits(n div 10)