Recursion in Standard ML
Our example demonstrates recursive functions in Standard ML. Here’s a classic example of factorial calculation using recursion.
In this Standard ML code:
We define the
fact
function using pattern matching. The base casefact 0 = 1
is explicitly defined, and the recursive casefact n = n * fact(n-1)
handles all other inputs.The
main
function demonstrates the usage of both thefact
function and a locally definedfib
function.In Standard ML, we don’t need to explicitly declare the type of recursive functions before defining them, as was necessary in the original example. The language’s type inference system can handle recursive definitions.
We use
let ... in ... end
construct to define local bindings within themain
function.String concatenation is done using the
^
operator, and we useInt.toString
to convert integers to strings for printing.
To run this program, you would typically save it in a file (e.g., recursion.sml
) and then use an Standard ML interpreter or compiler. For example, with the Standard ML of New Jersey (SML/NJ) system:
This demonstrates how recursion works in Standard ML, both for explicitly defined functions like fact
and for locally defined functions like fib
.