2

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...).

1
  • Can you rephrase the question or give an example? Why do you think that you cannot return a recursive function? Commented Nov 19, 2012 at 22:34

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

I am tying to implement a function f: (int->int) -> (int->int) that receives a function g as parameter and return h, where: h= $sum_{i=0}^{i}g(i)$ I tried to use "let" and after a lot of trying still it doesn't work well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.