0

This is just an example. These two functions are connected. You really want to call the one called lowest. It should then return the lowest number of the two. This of course won't work because you at the time of compiling the reducemax function you make a call to an at the time undefined function called lowest.

fun reducemax (i:int * int):int =
    if (#1 i) > (#2 i)
    then lowest(((#1 i)-1), (#2 i))
    else lowest((#1 i), ((#2 i)-1));

fun lowest (i:int * int):int =
    if (#1 i) = (#2 i)
    then (#1 i)
    else reducemax((#1 i), (#2 i));

I know I can use let to declare the reducemax function inside lowest, but is there any way around this? For example like in C, declare the function without defining it. I do understand the reducemax function need to know lowest will return an int and taking a int * int argument.

Horse SMith
  • 1,003
  • 2
  • 12
  • 25

1 Answers1

2

Just replace the second fun with and and remove the semicolons. This defines mutually recursive functions.

seanmcl
  • 9,740
  • 3
  • 39
  • 45
  • Ah, I vaguely remember learning this now!! Thank you. Is there any other way to do this, I mean like in C? – Horse SMith Nov 07 '13 at 14:51
  • Not really. That is, you can't declare functions before their use. You can implement mutually recursive functions without `and` (or even `fun`) using function references, with a technique called backpatching, which is something like what happens in C. However, you'll want to avoid that until you really know what you're doing in SML. – seanmcl Nov 07 '13 at 17:46