Search code examples
loopssmlnjml

Standard ml loop troubles


I am setting up a function that will simulate a loop until a condition is met.

My overall plan is to use recursion but I am trying to get the basics down first.

I got a basic function working using an If statement that is seeing what the value of X is. I plan to use recursion to use X as an counter but I will get to that later.

My main concern right now is, it seems I can only do 1 command after the "then" statement.

fun whileloop (x,a) =
    if (x<4)
    then a+1 
    else a;

So this function works perfectly fine, but it seems the only command I can do is the a+1. If I try to perform any other command after that, before the else...it fails.

For example, the below code will fail on me.

fun whileloop (x,a) =
    if (x<4)
    then a+1 
    print "Testing"
    else a;

my ultimate goal is to create a loop that will perform several actions over and over until X reaches zero. I need to perform like 5-6 actions using different functions.


Solution

  • You can evaluate several expressions in sequence using the semicolon operator:

    ( e1; e2; ...; eN )
    

    For example,

    fun iter n f = if n = 0 then () else (f n; iter (n-1) f)