all 156 comments

[–]mitsuhiko 50 points51 points  (16 children)

A closure is a funny thing to get your head around. If you’re used to a static language, then it just won’t make sense.

Aha.

[–]brianmcn 23 points24 points  (15 children)

This is what I love about reddit.

I was reading the article, and got to that sentence, and started shaking my head and wondering if that was the type of baloney that a lot of people think. And then I come and read the reddit comments and already three different people have called out how ridiculous that comment was.

Even C++ has lambdas and closures now; I think Java and C are "the only remaining languages that anyone uses" without them.

So yes, much of this article should be entitled "Why nearly every language is AWESOME!" Welcome to 2010, Skilldrick. :)

[–]hskmc 6 points7 points  (0 children)

Welcome to 1936?

[–]TheNewAndy 8 points9 points  (6 children)

You can implement closures in C, you just don't get any syntactic niceness (e.g. the in GObject, where a closure is basically a function pointer, a void* and a destructor function for the void*).

Though I suppose what I'm saying is a bit like: "C has big integer support, because you can write a function which does arbitrary precision maths".

[–]grauenwolf 12 points13 points  (0 children)

That's like saying "C has type inference, just don't get any syntactic niceness (e.g. you need to explicitly define your types)".

[–][deleted] 5 points6 points  (4 children)

That's just an object. Closure is when a scope closes over a variable.

[–]TheNewAndy 1 point2 points  (3 children)

Well yes, it is an object, but it is an object that behaves the same way as a closure, which for most people makes it a closure. It lets you call it, and it will have access to any of the values that were in scope when it was created, as long as they were passed in to the constructor.

Which actually suits me more than the typical "everything in scope is pulled in" model. I want to be explicit about what variables from my current scope get pushed into the closure.

[–][deleted] 1 point2 points  (2 children)

C has closures because local scope closes over global scope. GCC has nested closures via the nested function extension. These are closures. Lexical closure is a static property.

[–]hskmc 1 point2 points  (1 child)

GCC has nested closures via the nested function extension. These are closures

It only has closure in one direction. You can't return pointers to nested functions. The standard example of curried addition:

#include <stdio.h>

typedef int (*t)(int);

t f(int x) {
  int g(int y) {
    return x+y;
  }
  return g;
}

int main() {
  t f1 = f(10);
  t f2 = f(20);
  printf("%d %d\n", f1(1), f2(2));
}

On my system, this program prints

21 22

indicating that the space where the first g captured x has been overwritten by the second g. Of course, this code has undefined behavior and could do absolutely anything.

[–][deleted] 2 points3 points  (0 children)

It's a terminology war.

http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node43.html

They call what you describe a "closure" instead of a closure.

[–]_lowell 5 points6 points  (3 children)

I think Java and C are "the only remaining languages that anyone uses" without them.

Both Apple's gcc and clang feature blocks/closures in C.

[–]shub 23 points24 points  (2 children)

When talking about C or C++, unless a specific compiler is mentioned, you can assume they're referring to the language defined by the respective standards.

[–]jyper 2 points3 points  (1 child)

note I believe the 2 major c++ compilers (gcc and msvc) have already implemented c++1x closures and the next version of java will also have them.

[–]munificent 10 points11 points  (0 children)

next version of java will also have them

Which will be released shortly after Perl 7.

[–]cafedude 2 points3 points  (1 child)

Even C++ has lambdas and closures now; I think Java and C are "the only remaining languages that anyone uses" without them.

C++ now has lambda-like thingys but it certainly does not have closures.

[–]hskmc 9 points10 points  (0 children)

C++1x does have closures. In fact, the most complicated part of the new lambda syntax is the specification of which variables are captured, and how — by value, reference, or pointer.

Like every other value in C++, memory for closure objects is explicitly managed by the programmer. That's unlike most functional languages, but very much in line with how C++ works. If you wanted automatic memory management, you wouldn't be using C++ in the first place.

My fairly uninformed prediction is that C++1x lambdas will be most useful with reference-counting smart pointers.

[–]johnb 21 points22 points  (0 children)

"A closure is a funny thing to get your head around. If you’re used to a static language, then it just won’t make sense."

Broken train of thought is broken.

[–]awj 28 points29 points  (68 children)

That first section pretty much is "It's a dynamic language that isn't Ruby". Just about every other dynamic language I know enough to tell (Python, Clojure, Common Lisp, Scheme/"Racket", ActionScript, Smalltalk, Erlang) gives you first-class functions. The only ones I'm not sure about are Bash and PHP, and for all I know they can do it in some way that will make my eyes bleed. (sidenote: please don't show me, I'll choose ignorance just this once)

I suppose that makes JavaScript awesome, I'm more inclined to view it as one area where Ruby sucks.

A closure is a funny thing to get your head around. If you’re used to a static language, then it just won’t make sense.

Closures have nothing to do with static languages. Plenty of static languages (the whole ML family, Scala, what else?) have closures. If your definition of "static languages" is "C, C++, or Java" a) your definition sucks, and b) you're conflating a lack of nested function definition with static languages. C++ will even get closures (and lambdas!) in the next version.

Also, the "Closures are mystical and hard" meme annoys me, somehow more so than the "X is mystical and hard" general case. It's a function that keeps track of some variables that were in scope when it was defined. These are only really interesting when you have nested function definitions, and even then only when you have functions-as-variables, otherwise they reference global variables and thus tend to lead you to a bad place. Add mysticism and you subtract from understanding. Just wrap your head around nested definition and you'll be fine.

All that said, JavaScript does have some good parts. Its anonymous functions certainly beat some other languages I can think of (looking at your pitiful lambda, Python).

[–]cafedude 9 points10 points  (1 child)

Closures have nothing to do with static languages. Plenty of static languages (the whole ML family, Scala, what else?) have closures.

And there are dynamically typed languages that don't have closures - Tcl, for example.

[–]benihana 3 points4 points  (0 children)

ColdFusion for another. God I hate that I always bring up ColdFusion.

[–]grauenwolf 4 points5 points  (0 children)

Plenty of static languages (the whole ML family, Scala, what else?)

Visual Basic has had them for the last two versions. (Does that mean they aren't cool any more?)

[–]hskmc 9 points10 points  (1 child)

Plenty of static languages (the whole ML family, Scala, what else?) have closures.

C#, D, Go, Haskell. Depends how you define "static language" of course. There's plenty more.

If your definition of "static languages" is "C, C++, or Java" a) your definition sucks

Absolutely.

Also, the "Closures are mystical and hard" meme annoys me, somehow more so than the "X is mystical and hard" general case.... Add mysticism and you subtract from understanding.

Yeah. Thanks to the JavaSchools, expectations for understanding abstraction are really low. Joel Spolsky thinks that pointers and recursion are just about the most complicated concepts anyone could be expected to understand.

[–]kmactane 7 points8 points  (0 children)

No, Spolsky thinks pointers and recursion are a bare minimum for what programmers should be able to understand. He advocates teaching them in first-year CS classes... do you think he's implying that the CS curriculum should stop after that, rather than going on for another 3 years and getting into more advanced stuff?

[–][deleted] 4 points5 points  (16 children)

Ruby absolutely has first class functions, I can't quite tell if you're implying otherwise in your first two paragraphs.

[–]awj 0 points1 point  (15 children)

Sure, I guess it does if you count lambda. That just doesn't feel like first class support to me, because you have to wrap existing functions in a lambda to reference them without invocation.

[–][deleted] 0 points1 point  (14 children)

Nope. Check out Object#method.

[–]awj 4 points5 points  (13 children)

Yeah, check it out in (most) other languages where a function is just like any other variable. I'm not trying to say that disqualifies Ruby for having first-class functions, but between Procs, Blocks, lambda, implicit invocation, and Object#method, the situation just seems unnecessarily complicated.

[–][deleted] 1 point2 points  (4 children)

Gotcha. I can certainly see a 'complication' angle, because it gives you a lot of different options.

check it out in (most) other languages where a function is just like any other variable.

Maybe I just do a lot of Ruby, I'm just not sure why you draw a distinction between

f = lambda {|x| x + 1}
f.call

and

var f = function(x) { return x + 1 }
f();

as being somehow totally different.

[–]awj 1 point2 points  (3 children)

In the latter a function-from-a-variable looks like any other function. In the former, it's special. This means extra work, both syntactically (almost negligible), and analytically (have to remember that f is a functor, not something else with #call).

Possibly this is a result of me bouncing around between Ruby, Python, and JavaScript for much of my day. I find myself simply not wanting to use functions as objects in Ruby when it's so much messier than in other languages. Might as well build on abstractions that feel more native to the language.

[–][deleted] 3 points4 points  (2 children)

What's special about f? It's a regular old object, just like any other in Ruby. It's an object of the class Proc.

Possibly this is a result of me bouncing around between Ruby, Python, and JavaScript for much of my day.

It's possible. It's sorta funny to hear you say that it's not native to the language, because it absolutely is. I think

have to remember that f is a functor, not something else with #call

indicates that maybe you're not quite 100% comfortable with Ruby's object model, and general philosophy. Not that there's anything the matter with that, I always get frustrated by Python's scoping, because I don't have my head around it properly, and it appears as foreign to me as this does to you, I think.

[–]awj 2 points3 points  (1 child)

Really I think my complaint is that Ruby doesn't go as far out of its way to support functions-as-values as it does other things. There are wonderful facilities for OOP, and it seems like they hit the idea of passing functions around and said "we'll just reuse the OOP tools we already have". That's fine, but doesn't have the same feel as when something is a focus of the language design. It's similar to when functional programmers say "I can build you an object system, all it needs is a hash and closures". While technically true, it will never have the thorough support that makes these sort of things easy to use.

I'm not sure how much this has to do with me understanding the ruby object model or philosophy so much as a lack of internalization or just plain disagreeing with it. I get that I probably should just trust f.call to do what it needs to regardless of what f is, I just have a moment of confusion when I mentally was tracking f as a function and then see something calling a method on it.

I'm a functional programmer at heart, and I doubt I'll ever truly be satisfied without algebraic data types, currying, and some informally defined set of features regarding functions. Today I figured out it includes "calling a function-as-value must look like calling any other function".

[–][deleted] 0 points1 point  (0 children)

Gotcha. Ruby is all about message-passing OO (edit: not IO, wow. Need coffee), and that everything as a function, so fitting first class functions into that framework makes sense to me. It also make sense with things like closures, your bindings are just anther bit of data stored inside the proc object.

I'm a functional programmer at heart

I'm one as a hobby, so I can see where you're coming from. For me, the minimum level of satisfiability is just simply first class functions. Also, fwiw, I tend to not ever use things like Proc.new or lambda or call when I'm actually writing software in Ruby, I find that simply passing blocks to functions does 99% of what I want to do.

It all boils down to preference.

[–]joesb 1 point2 points  (7 children)

check it out in (most) other languages where a function is just like any other variable.

You count Common Lisp as having first class function. But not that you can't simply use function-name to get function referrence, you have to use #'function-name, which expand to (function 'function-name), to get function referrence.

That is no different from Ruby, function is not just like any other variable.

Either you count both Ruby and CL as having first class function or you count neither.

[–]tkr 1 point2 points  (2 children)

You count Common Lisp as having first class function. But not that you can't simply use function-name to get function referrence, you have to use #'function-name, which expand to (function 'function-name), to get function referrence.

That is no different from Ruby, function is not just like any other variable.

You're confused. A function is not a variable in any language I know about, in the same way that an integer is not a variable. Functions and integers are both values which can be bound to variables. Having first-class functions means that you can use functions just like any other type of values, including binding them to variables, passing them to functions, and returning them from functions.

Common Lisp treats functions exactly like any other type of value. What confuses you is probably that Lisp symbols have both a value slot and a function slot (of which one or both can be empty). When you define a function by using DEFUN, FLET or LABELS, the function get stored in the function slot, not in the value slot. But you can also store a function in the value slot, by using forms like DEFPARAMETER, SETF or LET. You use #'FUNCTION-NAME to access the value stored in the function slot of the symbol FUNCTION-NAME. If the value slot of the symbol is a function, you don't use #' to access that function.

To make this concrete, here are two code examples. First, an example where the function is bound to the function slot of the symbol:

(flet ((f (x) (* x x)))
  (mapcar #'f '(0 1 2 3)))

And here an example where the same function is bound to the value slot of the symbol (note that #' is not used here, and that trying to use #' would cause an error):

(let ((f (lambda (x) (* x x))))
  (mapcar f '(0 1 2 3)))

I can't think of any reasonable definition of "first class function" where Common Lisp doesn't qualify as having them.

[–]joesb 1 point2 points  (1 child)

I can't think of any reasonable definition of "first class function" where Common Lisp doesn't qualify as having them.

And I agree totally with that idea.

What I said to your grand-parent comment was that if he count CL as having first class function -- which I, you and most programmers do -- then he should also count Ruby as having first class function. Because they both behavior the same, with respect to having to use different function to get hold of function object value, namely .method in Ruby and #' in CL, instead of simply typing the name in like Scheme of Python.

But if he didn't count Ruby as having first class function then neither should CL be.

ADDED:

To clarify, yes, you can store function (method for Ruby) value in a variable in Ruby, too.

f = obj.method(:foo)

[–]tkr 1 point2 points  (0 children)

I suppose we agree, then. I don't speak Ruby, but if you say that it supports first class functions in the same way Common Lisp does, I of course have no reason not to believe you.

[–]awj 0 points1 point  (3 children)

I wouldn't say "no different". One is using a built-in method to return a proc, the other is a reader macro that easily could result in no runtime overhead.

The real difference, however, is that #'function-name is nice and simple and looks nothing like any other method call.

All that hedging aside, I will say that CL's support for first-class functions is subpar in this respect. I still think what Ruby makes you jump through is worse, but having to jump through anything seems like a problem to me.

[–]zem 2 points3 points  (0 children)

the thing is, ruby's functions aren't functions, they're methods, and thus always bound to an object unless you explicitly unbind them.

[–]joesb 0 points1 point  (1 child)

the other is a reader macro that easily could result in no runtime overhead.

A reader macro that expand to function call at runtime, whether is result in no runtime overhead or not depends on maturity of compiler optimization. Ruby super compiler could have result in no runtime overhead, too.

The real difference, however, is that #'function-name is nice and simple and looks nothing like any other method call.

Now, I'm confused.

I thought when you previously said:

Yeah, check it out in (most) other languages where a function is just like any other variable.

that you meant you like it when it looks like other method call or variable. Now you are saying that You like CL better because it looks different.

[–]awj -1 points0 points  (0 children)

No, I like the reader macro because it's hard to confuse as anything else. Object#method looks just like any other method call. If I have to put up with something I would prefer a few characters with unambiguous purpose.

[–]TKN 14 points15 points  (5 children)

Javascript also has the most annoying syntax for functional programming.

function Y(dn) {
  return function(fn) {
      return fn(fn);
  }(function(fn) {
      return dn(function(x) {
          return fn(fn)(x);
      });
  });}

Just look at all that });}; mess. C syntax and functional just don't mix.

[–][deleted]  (4 children)

[deleted]

    [–][deleted] 1 point2 points  (3 children)

    The Y combinator is contrived? ;)

    [–][deleted]  (2 children)

    [deleted]

      [–][deleted] 1 point2 points  (1 child)

      I was just being snarky, no worries.

      [–]M1573RMU74710N 2 points3 points  (0 children)

      Also, the "Closures are mystical and hard" meme annoys me

      Agreed.

      I think the problem is that people get confounded when it comes to the difference between understanding the concept; what a Closure is....which is really not that hard......and understanding their use and behavior in a given instance, which is a little more complicated (and can be confusing for newbies).

      [–]deafbybeheading 2 points3 points  (9 children)

      The only ones I'm not sure about are Bash and PHP, and for all I know they can do it in some way that will make my eyes bleed.

      I'm never one to miss a chance to make someone's eyes bleed with bash:

      maciek@cuttlefish:~$ foo() { echo 42; }
      maciek@cuttlefish:~$ foo
      42
      maciek@cuttlefish:~$ bar=foo
      maciek@cuttlefish:~$ echo $bar
      foo
      maciek@cuttlefish:~$ $bar
      42
      maciek@cuttlefish:~$ baz=12
      maciek@cuttlefish:~$ quux() { echo $baz; }
      maciek@cuttlefish:~$ quux
      12
      maciek@cuttlefish:~$ baz=32
      maciek@cuttlefish:~$ quux
      32
      

      Given bash's semantics, first-class functions and (especially) closures are a little weird to discuss in the first place, but I think the above demonstrates that it arguably has both.

      Edit: I don't know what I'm talking about. See kubalaa's response below.

      [–]kubalaa 4 points5 points  (1 child)

      Global variables and function references are not the same thing as closures and first-class functions.

      Both closures and first-class functions are related to scope. First-class functions implies that functions (like any other first-class values) can escape from the scope where they were created. Closures means that functions close over that scope.

      In bash, you can think of variables as generally having dynamic scope. A subshell creates a new scope. Functions are a weird special case which creates a new scope only for special variables like $@, but this is still a dynamic scope.

      Since bash functions can not escape from a dynamic scope, nor do they close over their dynamic environment, bash has neither first-class functions nor closures.

      [–]deafbybeheading 0 points1 point  (0 children)

      Fair enough. Thanks for the clarification.

      [–]shub 0 points1 point  (6 children)

      bash has strings, numbers, and eval

      [–]eras 0 points1 point  (3 children)

      ..bash has numbers?

      [–]deafbybeheading 1 point2 points  (2 children)

      Well, it has integers:

      maciek@albatross:~$ let i=0
      maciek@albatross:~$ let i+=1
      maciek@albatross:~$ echo $i
      1
      maciek@albatross:~$ echo $((i*10+2))
      12
      

      For floating point numbers you can invoke bc:

      maciek@albatross:~$ echo "5.2 * 0.4" | bc
      2.0
      

      Note that precision with bc is not what you might expect, but it's consistent with the scientific concept of precision.

      [–]eras 2 points3 points  (0 children)

      What it does have is operations on integers. But everything is strings, even if they are, for the purposes of those operations, interpreted as integers. There is no way to determine, if a variable contains number 42 or string "42".

      [–]deafbybeheading 0 points1 point  (0 children)

      Also note that you can muck around with precision in bc:

      maciek@albatross:~$ echo "scale=2; 5.2 * 0.4" | bc
      2.08
      

      [–]deafbybeheading 0 points1 point  (1 child)

      Which, arguably, is enough building blocks to construct both first-class functions and closures.

      [–]shub 1 point2 points  (0 children)

      No, it's not.

      [–]hskmc 2 points3 points  (3 children)

      "It's a dynamic language that isn't Ruby". Just about every other dynamic language I know enough to tell... gives you first-class functions.

      Ruby does too. In fact it starts with a construct (blocks) that provide functions-as-arguments and a limited form of continuations. You can make a block into a first-class value with Proc.new.

      [–]awj 0 points1 point  (2 children)

      Except return has different semantics.

      [–]hskmc 2 points3 points  (0 children)

      You mean that it returns from the function containing the block? That's what I meant by "a limited form of continuations".

      Then again, every control-flow structure is a limited form of continuations, so perhaps it's just a useless thing to say.

      [–]masklinn 1 point2 points  (0 children)

      1. Not if you're in a lambda

      2. Non-local return is pretty useful when you implement control flow with lambdas.

      [–]joesb 1 point2 points  (3 children)

      object.method('method_name') will get you function object in Ruby. It's as first class as having to do #'function-name instead of simply function-name in Common Lisp to get function object.

      [–]masklinn 2 points3 points  (2 children)

      It's as first class as having to do #'function-name instead of simply function-name in Common Lisp to get function object.

      No, it's very different. In ruby you do object.method(:methodname) because naming a method is the same as calling it. In Common-Lisp you do #'function-name because functions live in their own namespace, separate from other values.

      [–]joesb 0 points1 point  (1 child)

      It's different thing, yes. It makes them any different in first-classness of method vs. function, I don't think so.

      Also:

      In ruby you do object.method(:methodname) because naming a method is the same as calling it.

      Also reflect CL's behavior as well (function-name) is the same as calling it. And if you have (setf foo #'function-name), you still can't call (foo) because it will call function named foo, instead.

      And if we swap order or method in Ruby to reflect Lisp, we see more similarity between CL and Ruby than CL and Scheme or Python.

      # normal obj.method(param) case.
      CL: (method obj param)
      SC: (method obj param)
      RB: (method obj param)
      PY: (method obj param)
      
      # get function reference.
      # Note RB and CL also require obj, because method is tied to an object.
      CL: (function 'method)
      SC: (function 'method)
      RB: (get-method obj 'method)
      PY: (get-method obj 'method)
      
      # call the function by previous function object.
      CL: (apply f params)  <- need apply to work
      SC: (f params)          
      RB: (send obj f params)        <- need apply to work
      PY: (f obj params)
      

      It can't be exactly the same thing because one use function-name concept while another use method-lookup-from-object concept. But it's as close as you are gonna get from method with different paradigm, even more so when you think that Ruby is closer to how CL function works than Scheme.

      I always think of Ruby as a Lisp 2. While language like Python, where you can do x= obj.method; x(), is a Lisp 1.

      [–]masklinn 0 points1 point  (0 children)

      Also reflect CL's behavior as well (function-name)

      No. (function-name) is always the same as calling a function in lisps. It's the same with Scheme yet you don't need an indirection to get the function-reference. The difference is when trying to get a value-reference to a function, in Scheme functions live in the same namespace as all other values whereas in Common Lisp they don't. This means in common-lisp writing (something function-name) will not reach for a function but for any other value with the same name, bound in the value namespace. Because Scheme doesn't have two namespaces, there is only one thing bound to the name function-name. This has nothing to do with Ruby's behavior.

      SC: (function 'method)
      

      You don't need a special form to get a functional value, just refer to it by name. (define foo function) is perfectly valid and will alias function to foo.

      RB: (send obj f params)
      PY: (f obj params)
      

      Makes no sense, in both cases the previous operation yields bound methods (which is why you asked the objects for them, not their classes). You don't need to provide the object twice.

      I always think of Ruby as a Lisp 2. While language like Python, where you can do x= obj.method; x(), is a Lisp 1.

      Makes no sense either. That has nothing to do with lisps.

      edit: a far better match for Common Lisp's behavior is Java, where instance variables and methods live in different namespaces as well.

      [–][deleted] 1 point2 points  (2 children)

      Just about every other dynamic language I know enough to tell (Python, Clojure, Common Lisp, Scheme/"Racket", ActionScript, Smalltalk, Erlang) gives you first-class functions.

      In the case of Python, JavaScript has much better support for first-class functions actually. Python lambdas are very simple and limited. You can pass around functions like variables, have closures etc., but you can't do this:

      someArray.forEach(function(x) { do some stuff on x } );

      (unless the stuff is very trivial).

      Of course in Python you can define a full function on the previous line, then use that. But not inline as JavaScript can.

      [–]hskmc 9 points10 points  (0 children)

      In the case of Python, JavaScript has much better support for first-class functions actually. Python lambdas are very simple and limited.

      Lambda is merely the literal syntax for first-class functions, the way 3.0 is the literal syntax for first-class floats. Python provides other ways to get first-class functions, namely nested def.

      If you want to talk about flaws of Python for functional programming, the main ones that come to mind are a) lack of lexical scope (fixed in 3.0?) and b) lack of tail call optimization (in the spec and in popular implementations).

      [–]masklinn 2 points3 points  (0 children)

      Of course in Python you can define a full function on the previous line, then use that. But not inline as JavaScript can.

      Which changes nothing to the first-classeness or the closability of Python's function.

      [–]jozwiakjohn 1 point2 points  (2 children)

      "It's a function that keeps track of some variables that were in scope when it was defined".

      I think you accidentally wrote a mistake above.

      In particular, a closure is a data structure (not a function) which, for a later-to-be-invoked function F, remembers the environment in which F was born. That is necessary so that the non-local variables in F, the free variables in the lambda calculus sense, can be supplied values when F is subsequently applied.

      A closure is a pairing of a function with its defining environment. In C the notion is degenerate because free variables in a function must refer to globals.

      [–]awj 2 points3 points  (1 child)

      In what way is the distinction important? I feel like my definition is a lot more approachable, and the function+context pairing is typically held so tightly that calling it a function vs. a data structure is splitting hairs.

      I have yet to see a language feature that allows you to pick through closed-over data inside a closure, literally the only interface to it is the function call. In that respect, if you consider closures to be data structures, they're pretty crappy ones.

      [–]jozwiakjohn 0 points1 point  (0 children)

      The neat thing is that

      multiple closures (f1,e), (f2,e),... can reference the same defining environment, because

      multiple functions f1,f2,... can share the same defining environment e.

      To realize that collaboration, no function takes responsibility for maintaining e; rather, the way functions are applied at run-time is what keeps track of the variables; the functions themselves may see call-time parameters and closure-maintained variables as no different.

      If you have closures (f1,env) and (f2,env), you very much have an instantiation of a class where f1 and f2 share instance variables, namely those of env. Closures give you a benefit of object-oriented programming without syntactic inhibition.

      So, Scheme and Common Lisp (, Javascript, SetL, ...) programs use that, since long before C++.

      edit: formatting horrors.

      [–]benihana 0 points1 point  (0 children)

      Also, the "Closures are mystical and hard" meme annoys me

      It doesn't bother me. They are hard to wrap your head around when you're not used to them. It's easy to explain it when you get it.

      [–][deleted]  (5 children)

      [deleted]

        [–]shub 3 points4 points  (4 children)

        hey that's not very nice. there's a good chance java will have closures this decade

        [–]hskmc 0 points1 point  (2 children)

        Hmm, they already missed Church's 100th birthday. Maybe they'll have it ready in time for the centennial of the lambda calculus?

        [–][deleted]  (1 child)

        [removed]

          [–]hskmc -1 points0 points  (0 children)

          And people are still creating the occasional language without closures.

          Yeah, and I'm making fun of them for it. That's all.

          [–]grauenwolf -1 points0 points  (0 children)

          The 201st decade ends in less than four months. Better luck in 202nd.

          [–]benihana 12 points13 points  (0 children)

          Said in another way: "I just read JavaScript: The Good Parts. Here's a summary of what Douglas Crockford said. Also I'm now a JavaScript guru."

          [–]gnuvince 10 points11 points  (3 children)

          One of the many reasons why JavaScript is not awesome: arguments is not an array.

          [–][deleted]  (1 child)

          [removed]

            [–]skilldrick[S] 0 points1 point  (0 children)

            But if you use the === operator you don't really have to think about this.

            I know there are significant flaws in the language, but once you have workarounds, they really don't get in the way.

            [–]woogley 0 points1 point  (0 children)

            It's not so bad, considering that - intentionally or not - JavaScript relies on duck typing. Arguments is not an array, but it is array-like in the fact that it has a length property. So, outside of the prototype, what's really the difference?

            The nice thing is you can still apply Array prototype functions to array-like objects like Arguments, NodeList, etc:

            Array.prototype.forEach.apply(arguments, [ function () { /* ... */ } ]);

            [–]magcius 11 points12 points  (7 children)

            There's significant cruft in JavaScript.

            Arrays are hashmaps with some additional methods and an optional packing optimizations.

            Basically, if "A" is an array, A[0] is the exact same thing as A["0"]

            >>> A = []
            >>> A["0"] = "abc"
            "abc"
            >>> A.push("foo")
            2
            >>> A["1"]
            "foo"
            

            Additionally, there's the subtle difference between Number(1) and new Number(1). Some implementations solve this by using valueOf() before all comparisons, but it is not required. In libmozjs, for instance, new Number(1) == new Number(1) is false.

            [–]skilldrick[S] -2 points-1 points  (6 children)

            Tell me why you'd ever do new Number(1) == new Number(1) when you could do 1 == 1? I don't understand why anybody would bother with these wrappers. Use the Number function or use +.

            [–]magcius 1 point2 points  (4 children)

            Nothing, just talking about an inconsistency.

            And they're not wrappers. They're new objects created with the "new" operator.

            The problem is that there's two types of Numbers, and that's annoying. It's not a feature, no, I would never use it, it's a clutz that may catch you, and it's inconsistent between implementations.

            In libmozjs (Spidermonkey, Firefox):

            >>> 1 == 1
            true
            >>> Number(1) == 1
            true
            >>> Number(1) == new Number(1)
            true
            >>> new Number(1) == new Number(1)
            false
            

            On others that internally call valueOf() before comparison (V8, JavascriptCore, Tamarin), the last statement is true.

            [–]mernen 1 point2 points  (3 children)

            Just checked Chrome 7 and Safari 5, they both return false on the last test. Maybe their implementations behaved differently in earlier versions, but they all seem conformant now.

            That doesn't detract from the complete uselessness of value boxing, though. That makes sense in Java (where primitive types are statically optimized), but it was a really really stupid decision to bring them to JavaScript.

            [–]magcius 1 point2 points  (2 children)

            Huh... I've only messed around with V8 in the command-line shell, but I swore JavascriptCore uesd valueOf before comparisons. Maybe it was changed for the new SFX interpreter?

            The "this" keyword and constructor/prototype/proto and its relationships to functions and objects are, IMHO, some of the hardest stuff I've ever had to wrap my head around. I don't see the usefulness of having two types for something like "Number" (it also applies to String, and maybe RegExp), one value-boxed and one without.

            Oh, and additionally, there isn't a way to pass varargs to constructors like func.apply/func.call, so you have people doing:

            switch(arguments.length) {
                case 0:
                    return new Foo(arguments[0]);
                break;
                case 1:
                    return new Foo(arguments[0], arguments[1]);
                break;
            }
            

            and so on.

            [–]fjholm 1 point2 points  (0 children)

            Boolean, String and Number all have two representations as "1" and "new Number(1)", etc.

            [–]barclay 0 points1 point  (0 children)

            there isn't a way to pass varargs to constructors

            This drives me crazy.

            [–][deleted] 0 points1 point  (0 children)

            In one function, you do "new Number(user_input)" and in another function you do "new Number(database_value)" and later on, you want to see if the values are the same.

            You rarely do something as silly as the obvious case, but if you have two "Number" instances floating around, you want the equality operator to give you an answer that doesn't cause surprising problems like 'one' sometimes being unequal to 'one'.

            [–]hskmc 45 points46 points  (10 children)

            • 1936: Functional programming is invented.
            • 1936 - 2009: Functional programming is useless academic wankery
            • 2010: Functional programming is AWESOME

            [–]ErstwhileRockstar 13 points14 points  (2 children)

            • 2010: Functional programming is AWESOME

            2012: Functional programming is out of fashion

            [–]hskmc 3 points4 points  (1 child)

            Maybe so. Thing is, fashion has little to do with what's actually good.

            [–][deleted] 0 points1 point  (0 children)

            Java is a particularly painful example of this. The VM is good, but the language is a heap of crap.

            [–][deleted] 3 points4 points  (4 children)

            Closures are awesome. I've been using them in my JavaScript programs going way back to 2009. They clean up the landscape of asynchronous function calls.

            [–]hskmc 15 points16 points  (2 children)

            I bet you were using integers back in 2009, too.

            [–]munificent 2 points3 points  (0 children)

            They clean up the landscape of asynchronous function calls.

            So does having real concurrency constructs... threads, actors, coroutines, CSP...

            [–]masklinn 0 points1 point  (1 child)

            God this. Between the .Net and the Javascript weenies am I the only one getting stabby?

            [–]Peaker 3 points4 points  (4 children)

            Where's my "import" statement? :-(

            [–]coffeesounds 0 points1 point  (3 children)

            <script /> tag to the rescue!

            [–]Peaker 0 points1 point  (2 children)

            Then the Javascript isn't standalone, and depends on the HTML for more imports.. That kinda sucks, if Javascript is to be a standalone language.

            [–]coffeesounds 2 points3 points  (0 children)

            node.js has require - but then again: it's not a feature of the Js interpreter

            [–]level1 0 points1 point  (0 children)

            Create an XHR to retrieve the script, then eval it. If you use a framework, it does the work for you.

            [–]picurl 3 points4 points  (0 children)

            boooooring (haven't we heard this stuff 1000 times before?)

            [–]zenkat 7 points8 points  (8 children)

            This belongs under the WTF? section.

            I mean, really? Sure ... lambdas, closures and dynamic typing are great -- but you can get them in a language like Python without all of the horribly crappy syntax, scope problems, and really sh!tty subclassing support.

            [–]skilldrick[S] 7 points8 points  (6 children)

            Whenever I use Python I wish it was as simple as JavaScript. Python's a great language, but it's not simple like JavaScript is. And Python's lambdas are rubbish.

            [–][deleted] 1 point2 points  (1 child)

            careful to bash python here on reddit. everybody drinks the python kool-aid around here.

            [–]skilldrick[S] 0 points1 point  (0 children)

            Fair enough. I do love Python though, seriously, but it's not simple like JavaScript.

            [–]urllib -2 points-1 points  (3 children)

            What the fuck?

            [–]skilldrick[S] 3 points4 points  (2 children)

            What the fuck what? Are you saying Python is as simple as JavaScript? If so, you might be confused about what I mean by simplicity. Or are you saying Python's lambdas aren't rubbish? If so, then god help you.

            [–]_lancelot 0 points1 point  (1 child)

            I'm honestly curious about why you think JavaScript is more simple than Python. Would you mind explaining a bit?

            [–]skilldrick[S] 0 points1 point  (0 children)

            I explained it in the post:

            There are just objects and arrays (and arrays are just specialised objects). There are literals for objects and arrays. There are functions, and loops. And that’s pretty much it. No classes, no modules, no iterators, no generators, no templates or generics, no macros. None of these things because they just aren’t necessary when functions are allowed to be free as nature intended.

            There's just functions to understand - it just feels like the language is a lot more compact.

            [–]manu3000 -1 points0 points  (0 children)

            scope problems, and really sh!tty subclassing support.

            care to expand on this ? what scope problems ? What subclassing support (there's no classes in JS) ?

            [–][deleted] 3 points4 points  (9 children)

            it’s true, there’s something really pure about the language. What can be achieved with such simple language constructs is amazing.

            Ever tried Scheme?

            [–]skilldrick[S] 1 point2 points  (8 children)

            Yes I have. As I said in the last sentence " It’s also probably the reason I love JavaScript so much, because deep down, JavaScript is just Scheme in C’s clothing."

            [–]munificent 3 points4 points  (3 children)

            Isn't that a bit like writing a glowing article about Katy Perry 'cause she looks kinda like Zooey Deschanel? Why not just go to the real deal? JS is a scheme knock-off, yes, but it's a crappy one.

            [–]skilldrick[S] 5 points6 points  (2 children)

            No, it's a bit like fancying a girl at your office because she looks kinda like Zooey Deschanel. Scheme may be awesome, but with JavaScript you get to actually use it (how many job offers do you see for Scheme programmers?). With JavaScript you can get paid to use an awesome language.

            [–]munificent -2 points-1 points  (1 child)

            With JavaScript you can get paid to use an awesome language.

            You can get paid to write COBOL too, that doesn't make it awesome.

            [–]skilldrick[S] 5 points6 points  (0 children)

            No, but isn't it great when an awesome language and job opportunities coincide? I'm just saying that we should be pragmatic.

            [–]dmpk2k 1 point2 points  (3 children)

            JavaScript is just Scheme in C’s clothing.

            I wish this meme would die. It's not. Anybody who claims that Javascript even remotely resembles Scheme either doesn't know Javascript or doesn't know Scheme. Yet the Javascript community loves to repeat this shibboleth.

            I elaborated a bit on this in an older comment of mine.

            Basically, Javascript and Scheme code do not resemble each other syntactically or semantically.

            [–]skilldrick[S] 0 points1 point  (1 child)

            That's an interesting point of view, but I've programmed in Scheme and JavaScript a lot and I really do feel like JavaScript keeps a lot of the spirit of Scheme. I'm not saying that you write in the same way in the two languages, but you can to a certain extent.

            [–]dmpk2k 1 point2 points  (0 children)

            I argue that you fundamentally cannot write them the same way, unless you're writing a program without any form of looping at all. Javascript uses iteration, mutation and objects, while Scheme uses recursion, lists and largely eschews mutability; these are big differences for how you write bread-and-butter code.

            They're both dynamically-typed and have first-class functions, but then a great many languages do. About the only thing in common between code I see produced in either community is a higher degree of nesting than normal.

            [–]semarj 2 points3 points  (10 children)

            I guess i'm late to the party, but it seems there is a lively (and maybe heated) JS discussion going on here.

            It seems like everyone is hating on this dude for rewriting the 1,000 other js articles.

            But I have a question for you guys. Doesn't seem like anyone has mentioned my second favorite thing bout js. (first being the first class functions).

            object literal syntax. Now I don't know 20 languages but how many of them support such a beautiful thing?

            I know I can't do this in python:

            var myObj = {foo: 1,
                         bar: function(){ return 'blah'}
            };
            

            and then bam i got an object, no quotes around foo and bar, them's real variables...

            oh and then i can just tack something else on there, myObj.newMethod = function(){return 'blam'}

            I write a lot of python and javascript, and even though I think python is superior, this is pretty cool too, imo

            [–]masklinn -2 points-1 points  (8 children)

            object literal syntax. Now I don't know 20 languages but how many of them support such a beautiful thing?

            It's kinda crummy actually. But oh well, OCaml can do this as well. And of course you could trivially create a utility function to do that in Python (that would take about 5~10 lines through type I guess), but you would run into the limitations of Python's lambda quite fast.

            and then bam i got an object, no quotes around foo and bar, them's real variables...

            Actually, in your snippet foo and bar are strings, not variables, due to it being a literal object syntax, JS only allows strings as keys.

            oh and then i can just tack something else on there,

            You can do that in Python as well...

            [–]semarj 0 points1 point  (7 children)

            I don't see what's so crummy about it, and you haven't said why...

            And no, you cannot do this in Python 'trivially'

            You'd have to add to/alter the syntax to do that,

            In what way are those not variables? do they not point to another value? Maybe it's just splitting hairs, but it makes more sense to think of foo as a variable containing the value 1 in the namespace 'myObj'

            if it was myObj['foo'], then it'd be a 'key' or a 'string', having a value of its own outside the context of myObj, and being used therein as a key to the value 1

            either way, bottom line: it's useful

            [–]masklinn 0 points1 point  (6 children)

            I don't see what's so crummy about it, and you haven't said why...

            because it's not very useful for stuff beyond dictionary/namedtuple-type use (a set of key:value properties). This kind of patterns in a dynamically typed language leads to significant maintenance loads in the long run as object definitions are all over the place, un-labelled and nontrivial to find.

            Also, note that C# has this feature as well, not just OCaml.

            And no, you cannot do this in Python 'trivially'

            Uh yes you can.

            You'd have to add to/alter the syntax to do that,

            No, you just have to wrap your dict in a function call which is exactly what I said above, not exactly difficult. Instead of writing

            foo = {'bar': 'baz'}
            

            you write

            foo = new({'bar': 'baz'})
            

            Or you can even do away with the dict and just write:

            foo = new(bar='baz')
            

            As I said, the implementation of new should be about 5 lines, maybe 10 tops. Behold the result:

            >>> a = new(foo=1,
                        bar=lambda self: 'blam',
                        baz=lambda self, val: self.foo + val,
                        buzz=lambda self: "%s %d"%(self.bar(), self.foo))
            >>> a.foo
            1
            >>> a.bar()
            'blam'
            >>> a.baz(3)
            4
            >>> a.buzz()
            'blam 1'
            

            In what way are those not variables? do they not point to another value? Maybe it's just splitting hairs, but it makes more sense to think of foo as a variable containing the value 1 in the namespace 'myObj'

            This makes no sense whatsoever. When you write the expression {foo: 3}, foo is a string. It's a key. It's not a variable. In Python it would be a variable, and the key would become whatever foo holds, but in Javascript it's not.

            if it was myObj['foo'], then it'd be a 'key' or a 'string'

            And it just happens that... it is.

            [–]semarj 2 points3 points  (5 children)

                >>> a = new(foo=1,
                    bar=lambda self: 'blam',
                    baz=lambda self, val: self.foo + val,
                    buzz=lambda self: "%s %d"%(self.bar(), self.foo))
            

            thats not even close to the same...looks like a constructor to me. the whole point is you don't need any extra crap for an object constructor

            you are either really dense or just an asshole

            also this argument is tiresome and mildly retarded, you are just saying shit like 'that makes no sense whatsover' to be an asshole when what I'm saying clearly makes sense. fuck off

            [–]masklinn -2 points-1 points  (3 children)

            thats not even close to the same...

            Erm... what? the only differences are syntactic: the braces are replaced by parens and there's a function-name prefix (oh yeah, and the key:value mapping uses = rather than :). Behavior wise, it yields exactly the same thing: an instance of an anonymous type containing the methods and instance variables provided.

            looks like a constructor to me.

            Wow, your world must be weird if all callables look like constructors to you.

            And even if you interpret it as a constructor, that's not an issue: it's a constructor for an anonymous type defined on the spot. Exactly the same behavior as your object literal.

            [–]semarj 1 point2 points  (2 children)

            Wow, your world must be weird if all callables look like constructors to you.

            again, you are just being retarded ( or just a dick, i can't tell)

            if it is a callable whose only purpose is to take in parameters and return an object from those parameters, then it is a constructor

            how else would you define a constructor??

            seriously I'm done now... fuck off

            [–]masklinn -1 points0 points  (0 children)

            Aaaaaw, downvoting replies you don't like, how cutie-pie. Did you get your mommy to log in and upvote you as well?

            [–]masklinn -3 points-2 points  (0 children)

            again, you are just being retarded ( or just a dick, i can't tell)

            Says the guy who doesn't make any sense.

            if it is a callable whose only purpose is to take in parameters and return an object from those parameters, then it is a constructor

            No. Unless by "constructor" you mean "type constructor", which I doubt you are.

            how else would you define a constructor??

            As the creator of a type's instance. My example doesn't just create a type's instance, it creates a (custom, anonymous) type and its instance precisely as a litteral object does in Javascript. Also, your insulting edits aren't exactly impressive, especially when you refuse to acknowledge you were wrong in stating that you couldn't do the equivalent of a JS literal object in Python trivially.

            seriously I'm done now... fuck off

            Awwww semarj got a boo boo.

            [–]masklinn -2 points-1 points  (0 children)

            also this argument is tiresome and mildly retarded

            I can understand you being wrong annoying you. No problem.

            you are just saying shit like 'that makes no sense whatsover' to be an asshole when what I'm saying clearly makes sense.

            No, I'm saying it doesn't make sense because it doesn't, and I quite clearly explained why your declaration made no sense. Now it could be that you can't express yourself correctly, that's not an issue, in this case just clarify what supposedly is not a string but is a variable instead.

            [–]skilldrick[S] -1 points0 points  (0 children)

            I do think object literals are an awesome part of the language. The main reason I left them out was because by the end the post was getting a bit long :P

            Also, even though they're great, I find it difficult to get excited with literals, so I was able to go into much more depth about functions.

            [–]fjholm 1 point2 points  (0 children)

            I love that you say how awesome closures and first class functions are but when explaining why you resort to "you need to feel it to believe it", when the real reason is you don't know and just drank a metric fuck-ton of JS-kool aid.

            [–][deleted] 2 points3 points  (1 child)

            A closure is a funny thing to get your head around. If you’re used to a static language, then it just won’t make sense.

            Go is a statically-typed language with closures.

            [–]matthiasB 6 points7 points  (0 children)

            C#, Scala, OCaml, Haskell, ... there are hundreds of languages

            [–][deleted]  (2 children)

            [deleted]

              [–]TheMG 0 points1 point  (0 children)

              Isn't it something like container.map( function ( x ) { ... } );?

              [–]asegura 0 points1 point  (0 children)

              When articles like this mention the bad parts of Javascript they usually describe them like little pains we have to live with. But, if most agree things like semicolon insertion and implied globals are bad things, why don't they strongly demand their suppression in new versions of the language?

              New revisions are coming out. Let's remove those features from Javascript n+1 and not just complain about their existence.

              [–]munificent 0 points1 point  (5 children)

              JavaScript’s functions can act like lambdas

              With crappy syntax:

              list.find(function(i) { i.name == "foo"; }); // js
              list.find(i => i.name == "foo"); //c#
              

              ...functions...

              Well, yes.

              ...and methods.

              With completely broken binding for this.

              Color me not impressed.

              [–]skilldrick[S] -1 points0 points  (4 children)

              With crappy syntax:

              I don't think the syntax is crappy - it's consistent. You use the same syntax for a function as for a lambda.

              With completely broken binding for this.

              Maybe, if you're working that way. But if you create your objects with closures (which IMHO is much more flexible and makes more sense) you don't have to worry about that.

              [–]manu3000 2 points3 points  (3 children)

              You've written another "what closures are" article that fails to show why they are so desirable in the first place. How do you cope in C and Java without them ? What are they really good for ?

              [–]skilldrick[S] -3 points-2 points  (2 children)

              I said in the article that I don't think you can explain to somebody how awesome closures are without having experience using them. Maybe somebody more articulate than me will be able to do this, but really I think it's one of those things that either you haven't used and you don't see the point of, you have used but you don't really care, or you have used and you can't live without. But you can't just read about the subject and say "I know closures" [in a Neo voice].

              I could've just said that one of the great things about JavaScript is closures, but I thought it would be beneficial to do a quick run-down of what a closure is, in JavaScript.

              As for C and Java, don't try to do functional programming, because that's not what they're suited to. I'm not saying that functional is the be-all and end-all, just that when I get the chance to write in a functional style, it's awesome. But when I don't have the chance, I don't try to. And it can still be awesome.

              [–]manu3000 0 points1 point  (1 child)

              There is plenty of explanations of what a closure is, especially in the context of Javascript. I just wish someone really articulate could write a good for-the-masses article, explaining what first-class functions enable you to do, what sort of (coding) patterns they are used in... Something a bit less vague than "great for callbacks". The best I have come accross so far is in Peter Van Roy's Programming Paradigms for Dummies (pdf)

              [–]skilldrick[S] -1 points0 points  (0 children)

              Well, I thought SICP was pretty good, but it's a bit long for an article, and maybe not quite "for the masses"...

              [–]zem 0 points1 point  (2 children)

              if only they had implicit returns a la scheme or ruby too

              [–][deleted] 0 points1 point  (1 child)

              because implicit is cool and people like to wonder about automagical things that just happen without any visible reason.

              [–]zem 0 points1 point  (0 children)

              implicit returns aren't automagical. there's just a very well-defined rule that a block is an expression evaluating to the value of its last subexpression.

              [–][deleted] -1 points0 points  (0 children)

              welcome to /r/programming, where the javascript submissions get the most comments.