Search code examples
sml

SML - Error: operator is not a function [tycon mismatch]


I'm trying to create a program that will sum the digits of a large factorial and this is what I'm doing:

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


fun factLarge 1 = IntInf.toLarge 1
  | factLarge n = IntInf.toLarge n * factLarge(n-1)


sumDigits (factLarge 100)

But I'm getting an error on sumDigits (factLarge 100) and I don't know how to fix it.

20.sml:8.19-11.26 Error: operator is not a function [tycon mismatch] operator: IntInf.int in expression: (factLarge (n - 1)) sumDigits


Solution

  • That specific error is due to the way you must be pasting your code into the REPL. It can't figure out where the definition of factLarge ends. Put a semicolon at the end of that definition and this error will go away (or, even better use the command use filename.sml; rather than copy-pasting code):

    fun sumDigits n = 
      if n < 10 then n
      else
        n mod 10 + sumDigits(n div 10);
    
    fun factLarge 1 = IntInf.toLarge 1
      | factLarge n = IntInf.toLarge n * factLarge(n-1);
    
    sumDigits (factLarge 100);
    

    Unfortunately, this trades a superficial error for a deeper error:

    stdIn:40.1-40.26 Error: operator and operand don't agree [tycon mismatch]
      operator domain: int
      operand:         IntInf.int
      in expression:
        sumDigits (factLarge 100)
    

    The problem is that your sumDigits is expecting an int, not an IntInf.int. You have to put the appropriate type annotation on the definiton of sumDigits for this to work correctly. Since this seems to be homework, I'll leave it for you to work out.