Question

I am looking for a function for : int * int * (int -> unit) -> unit. I need this to print a list of numbers. To be more specific, I have a function f num = print ((Int.toString num)^"\n"). So far, I have this:

fun for(from,to,f)=
        if from=to then [f(to)]
        else f(from)::for(from+1,to,f)

which gives me a return type of unit list. How can I call for function without appending to earlier result?

Was it helpful?

Solution

The () you want to return is the () from the last call to f - that is, the call from the then branch.

Generally speaking, whenever you want to do two things, and only return the result of the second thing, you use the following syntax:

(thing1;thing2)

For example:

(print "foo\n"; 2 + 3);

Would print out the string "foo\n", and then return 5.

So now, let's look at the two branches of your code.

fun for (from,to,f) = if from = to 
                      then ...
                      else ...

In the then branch, we simply call f on to. f already returns (), so we don't do anything more with the result:

fun for (from,to,f) = if from = to 
                      then f to
                      else ...

The else branch is slightly more complicated. We want to call f on from, and then make a recursive call. The return type of the recursive call is unit, so that's what we want to return:

fun for (from,to,f) = if from = to 
                      then f to 
                      else (f from;for (from+1,to,f));

Another thing: What happens if you do this?

for (4,3,f)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top