John Evans' Blog

Polymorphic function arguments

by on Nov.17, 2008, under Uncategorized

I just had this curious thought…

If you’re programming, you call functions a lot. Functions often have parameters. Sometimes they can have a lot of parameters. Sometimes it’s hard to remember which parameters are which; like, if the function is supposed to be called like “function(int amount, int x, int y)” and instead you give it the parameters “function(x, y, amt)” then something’s going to go wrong. Now, granted, in modern IDEs and editors it’s usually quite simple to look up the function definition and make sure you’re calling it correctly.

However…What if you could call the function arguments in some other order, as long as you knew what they were? Something like this: “function(x: 2, y: 3, amount: 1)”. There would be some specifier to let the compiler associate the parameters with their values.

I feel like I’ve seen some language that had this facility, but at the moment I can’t remember what it was.

:,
4 comments for this entry:
  1. morbid_curious

    Python allows you to specify a function prototype that takes a dictionary as a parameter. E.g.

    >>> def f(**args):
    	for k in args.keys():
    		print "%s: %s" % (k, args[k])
    
    >>> f(a=1, b=6, fred="flintstone")
    a: 1
    b: 6
    fred: flintstone

  2. johnevans

    Python! Cripes, another language? I just learned JavaScript! WHAT MORE DO YOU WANT FROM ME?

    …anyway…hm…looks like just passing an associative array. Like a Perl hash. You could do that same sort of thing in Perl.

  3. morbid_curious

    It’s very similar to passing an associative array or hash, yes. I’ve done that same sort of thing in Perl too 🙂

  4. maramala

    Pretty much.

    And since you’re doing Javascript, here’s a heads up: This may be hearsay, but according from a developer acquaintance who’s in the W3C, the upcoming updated versions of scripting languages might also feature the flexible function parameters, among others.

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...