1

I am a beginner in mozart oz, and I would like to write a simple higher order function, like {{Add 1}2}, the result of which has to be 3. I guess this is something like nested call in C, where a function could call itself? I am not sure how to define this function, should I write

declare
fun {Add I}

or

declare
fun {{Add I}J}

? And I really don't know how to finish such a function. I have tried several times, but I never have it worked.

phil
  • 255
  • 4
  • 16

2 Answers2

1

Something like this should work (untested):

declare
   fun {Add I}
      % define a local function which adds I to its argument
      fun {Adder J}
         J + I
      end
   in
      % returns this new function
      Adder
   end

{Show {{Add 1} 2}}  % should print 3

% or more verbose:
declare
   Add1 = {Add 1}
   {Show {Add1 2}}
wmeyer
  • 3,426
  • 1
  • 18
  • 26
  • I get "Variable Adder has not been introduced." – Tadgh Sep 14 '13 at 02:50
  • @Tadgh: Indeed, there was an error. I added the "in" keyword to separate the declaration of the local adder from the function body. – wmeyer Sep 14 '13 at 10:01
  • Thanks. Why exactly does this work? The Function is declared only locally, and then the return value of the entire function is "Adder"? – Tadgh Sep 14 '13 at 12:12
  • @Tadgh: Yes, the return value of `Add` is the function `Adder` (i.e. functions are values). It is not a problem that `Adder` is declared only locally. The function (and the code behind it) is just a value like any other value and will be destroyed/garbage-collected only when no variable references it anymore. - In fact, `Adder` _has_ to be defined locally because it "closes over" the parameter `I`. A new function `Adder` is created whenever `Add` is called. – wmeyer Sep 14 '13 at 13:12
0

concise code:

fun{Add I}
   fun{$ J} I+J end
end
yakoudbz
  • 903
  • 1
  • 6
  • 14