3 ms·
are functions being passed/returned as closures?
by lispm 13y ago
are functions being passed/returned as closures?
- tokipin 13y agoif you're asking whether functions in Mathematica are first-class values, then yes. everything in Mathematica is first-class. functions are just symbols that have associated pattern-matching rules in the form f[___], otherwise they are the same as any other symbol. you can do, for example: RandomChoice[{Plus, Times}][2, 3] where the result will be either 5 or 6. in more explicit form: If[RandomReal[] < .5, Plus, Times][2, 3] example of an "anonymous" function: (#1^2 + #2^2 &)[2, 3] square of all numbers from 1 to 100: #^2 & /@ Range[100] simpler form: Range[100]^2 all pairwise products of the first seven prime numbers (among themselves): Times @@@ Tuples[Prime /@ Range[7], 2] etc.
- lispm 13y agoI'm asking if first class functions also can be closures. Does it use lexical binding?
- tokipin 13y agoi think i answered that question already, which is yes, but technically no. here is a rough Javascript version of the original example: makeObj[] := Module[{obj, i = 0}, obj["inc"] := ++i; obj["dec"] := --i; obj[] := i; obj]; makeObj = function() { var i = 0; var obj = function(in) { switch(in) { case "inc" : return ++i; case "dec" : return --i; case undefined: return i; }; }; return obj; };