coffeescript icon indicating copy to clipboard operation
coffeescript copied to clipboard

capturing trailing function in params list

Open mynyml opened this issue 15 years ago • 17 comments

jacobthornton and I would like to propose a simple method of capturing the trailing function of a parameter list, a common usecase when passing callbacks.

foo = (a = 1, b = 2, &callback) ->
  console.log a
  console.log b
  console.log callback

foo 8, 9, ->
#8
#9
# [Function]

foo 8, ->
#8
#2
# [Function]

foo ->
#1
#2
# [Function]

foo 8, 9
#8
#9
# undefined

The ampersand semantic is similar to Ruby's, so it's not entirely new. A possible implementation would be the following.

function __tailingFn (args) {
  for (var i = args.length; i--;) {
    if (typeof args[i] == 'function') {
      var fn = args[i];
      args[i] = undefined;
      return fn;
    }
  }
}

function foo (a, b, fn) {
  fn = __tailingFn(arguments);
  if (a == null) {
    a = 1;
  }
  if (b == null) {
    b = 2;
  }
  // ...
}

This is especially useful in cases where a function takes optional arguments in adition to a callback, as it avoids having to place them after it (e.g. setTimeout())

mynyml avatar Mar 23 '11 21:03 mynyml

+1

cloudhead avatar Mar 23 '11 22:03 cloudhead

You can already do this trivially, although it's not quite as pretty.

(args..., fn) ->

becomes

var __slice = Array.prototype.slice;
(function() {
  var args, fn, _i;
  args = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), fn = arguments[_i++];
});

Then you can split up args using a deconstruction assignment or whatever.

erisdev avatar Mar 23 '11 23:03 erisdev

@erisdiscord args... is pretty convenient, but it doesn't allow for default vals in params, and is especially not great documentation-wise. Also imo args... generally means the function accepts a variable number of args, which is not the case in the example function above.

mynyml avatar Mar 23 '11 23:03 mynyml

+0.5 :-)

The proposed construct looks good, though I have a feeling that using & is not good because it's used in JS bitwise operation. However, since it's unary, then it may work.

OnesimusUnbound avatar Mar 24 '11 00:03 OnesimusUnbound

@mynyml Good point. How about something like this?

getBlock = (argsObject) ->
  lastIndex = argsObject.length - 1
  if lastIndex >= 0 and typeof(argsObject[lastIndex]) is 'function'
    Array::pop.call argsObject
  else
    null

Your example function would look like this:

foo = (a = 1, b = 2) ->
  callback = getBlock(arguments)
  console.log a
  console.log b
  console.log

The function is removed from the arguments object if there is one.

erisdev avatar Mar 24 '11 00:03 erisdev

@erisdiscord

It will not work for foo 1, -> and foo -> since foo 1, -> will replace b with -> and in foo ->, a will be replaced with ->

OnesimusUnbound avatar Mar 24 '11 00:03 OnesimusUnbound

Ah right, I forgot that arguments aren't aliased to the elements of the arguments object. You got me. :)

erisdev avatar Mar 24 '11 00:03 erisdev

I'd like to remark that in Ruby, one needs the use the ampersand not only when defining the function, but also when calling it, unless Ruby's special block syntax is used. Using regular lambdas, your example would look somewhat like this in Ruby 1.9.2: def foo(a = 1, b = 2, &callback) puts a puts b puts callback end

foo 8, 9, &lambda{}
#8
#9
#<Proc:...>

foo 8, &lambda{}
#8
#2
#<Proc:...>

foo &lambda{}
#1
#2
#<Proc:...>

foo 8, 9
#8
#9

But without the ampersand, you'd get foo lambda{} #Proc:... #2

odf avatar Mar 24 '11 04:03 odf

You should look at my proposal for "single-value splats" at #1091, which I believe is a more general solution to the problem you've raised. The proposal would allow you to make any argument optional using ?, and to assign a default value to an optional argument with ?= (instead of the existing = which checks nullity rather than the number of given arguments).

With that syntax, your first example would be written as

foo = (a ?= 1, b ?= 2, callback) ->

It's nice and consistent: Anything followed by ? or ?= is optional, anything followed by ... is splatted, and arguments without extra symbols take priority.

TrevorBurnham avatar Mar 24 '11 17:03 TrevorBurnham

@odf That's true of Ruby when you want to pass a variable as the block, but only because the block is handled specially, and that Ruby doesn't quite have first class functions the way js does (details aside). This proposal looks for the trailing function argument, so special syntax when calling the function isn't necessary. Imo that keeps it simple.

In the case that we'd rather restrict this behavior to the very last argument, it'd be possible to add this restriction at the compiler level (i.e. only allow & before the last arg).

mynyml avatar Mar 24 '11 17:03 mynyml

@erisdiscord The syntax you proposed wouldn't work, unfortunately, because if your block took arguments it would become ambiguous (among others). It has been proposed before and rejected in favor of simply dropping the parentheses.

This proposal only targets the parameter list, not the argument list.

mynyml avatar Mar 24 '11 17:03 mynyml

@mynyml: I guess I wasn't very clear. The point is that it often makes sense for the trailing function argument and the preceding arguments to both be optional, which may lead to ambiguities, particular since someone might find it useful to pass functions in other positions than the last, as well. So one has to think of ways of avoiding those ambiguities.

I described how Ruby deals with those ambiguities, namely by prepending the ampersand at the call site, as well. This has nothing to do with the fact that Ruby allows special syntax for "the block".

odf avatar Mar 24 '11 21:03 odf

@odf You're right about the potential ambuguity. I think what you're describing is the second scenario of the original post,

foo 8, ->
# 8
# 2
# [Function]

but where the intent would be for the function to be the second argument, b. The problem with disambiguiating this is that the & would have to be used every time at callsite, since there is no special syntax to notificy it's the trailing function (where Ruby has the block syntax).

It's also the reason we're calling this behaviour 'trailing function'; whatever the last function is, it's assigned to the & param. If a function is expected to be passed as other args, then the signature should probably not use &.

mynyml avatar Mar 26 '11 17:03 mynyml

+1

Not really got a view on the final syntax, but I've had experience of code where this would be very handy as the current way just seems ugly

For example:

foo = (a, b, fn, c = true) ->
    # Something in here

foo 1, 2 () ->
    # Callback
, false

If the callback function gets long, then it's difficult to place the false at the end and be readable.

tanepiper avatar Apr 10 '11 00:04 tanepiper

Sorry folks, but this idea would be importing a hacky workaround from Ruby where none is needed in JavaScript. The reason why a special ampersand is needed in Ruby is because blocks aren't otherwise first-class values, but instead a special form. In JavaScript, functions are arguments like any others, and don't deserve special treatment or special syntax in an argument list.

jashkenas avatar Apr 21 '11 01:04 jashkenas

I think this might be missing the main point simply b/c of the notation is like Ruby's. Really it could just mean "parse this last argument first". Conceivably one could put more than one such argument on the end.

trans avatar May 31 '11 03:05 trans

@trans This was indeed the original intent. I probably should not have used the ampersand in the proposal as it gave some commenters the impression it was a feature port. Jashkenas was right about CS not needing Ruby's block functionality, but that wasn't what the proposal was suggesting. "a simple method of capturing the trailing function of a parameter list" is all it is.

In general I'd be happy doing this on my own with a custom function, but the problem is that there's no way to do it manually and also keep the default values specified in the param list, as that requires calling the function before the default values are set (which is what the second code block in the OP illustrates).

Here's a real use case: https://github.com/mynyml/pathname/blob/master/src/pathname.coffee#L89 (notice defaults are set after the function call instead of in the params list).

I use this type of function signature fairly frequently in my cs code (i.e. last function arg is the callback), so to me this would be a great feature addition.

mynyml avatar May 31 '11 17:05 mynyml