poli
poli

Reputation: 75

Returning a recursive function in ML

How can I return a recursive function in ML?

As far as I know recursive anonymous functions cannot be returned and only anonymous functions can be used as returning value(if the returning value is function...).

Upvotes: 2

Views: 382

Answers (1)

Andreas Rossberg
Andreas Rossberg

Reputation: 36098

Would this be the kind of example you are wondering about?

fun f n =
   let
      fun g k =
         if k = n then [] else k :: g (k-1)
   in
      g
   end

You can only make a recursive definition by naming it, but that's not a problem, because you can write a let expression anywhere.

Update to answer comment more specifically:

fun f g =
   let
      fun h 0 = g 0
        | h i = h (i-1) + g i
   in
      h
   end

(A more efficient implementation would make h tail-recursive.)

Upvotes: 3

Related Questions