views:

1153

answers:

33

There are some gadgets/features for programming languages that I like a lot because they save a lot of coding or simply because they are magical or nice.

Some of my favorites are:

  • C++ increment/decrement operator: my_array[++c];
  • C++ assign and sum or substract (...): a += b
  • C# yield return: yield return 1;
  • C# foreach: foreach (MyClass x in MyCollection)
  • PLSQL for loop: for c in (select col1, col2 from mytable)
  • PLSQL pipe row: for i in 1..x loop pipe row(i); end loop;
  • Python Array access operator: a[:1]
  • PLSQL ref cursors.

Which are yours?

+1  A: 

Perl is full of neat "gadgets" but some I like are the //, s//, <=> and <> operators - that last one particularly for the way it magically either reads from files listed on the commandline or from standard input, the others just because they are concise and useful.

Ada has a few nice features that would be nice to have in other languages, such as rendesvous and protected types.

Other favourites which are in various languages are foreach and the ternary (?:) operator, although you have to be careful not to make a mess with it by trying to cram too much into one line.

lemnisca
If the line gets too long, break it up. That doesn't mean you cannot use the ternary.
Svante
+1  A: 

Haskell's currying is pretty fancy.

Stefan Mai
+6  A: 
  • python generators and list comprehensions
  • haskell type unification and type variables
  • jquery chaining with add, andSelf, etc
Nick Retallack
+1 for generators!
bedwyr
+1  A: 

I <3 javascript's "with" and best closure implementation in any language

Also feeling the "x?y:z" operator and C#'s "a??b"

annakata
What's your opinion on Douglas Crockford saying one should NEVER use the with statement...?
defmeta
Well it's hard to argue this 300 chars, but Crockford's assertion is that *with* is "prone to error" which strikes me as the same kind of pessimistic logic which crippled *switch* in C#. imho with is no more dangerous than if can be, and any problems therein are because of the coder not the language
annakata
Really? See closures in JavaFX ^^!
Helper Method
+11  A: 

C#:

  • Lambda expressions
  • Null coalescing operator (??)
  • Query expressions
  • Iterator blocks, as mentioned in the question
  • Object and collection initializers
  • Extension methods
  • Automatically implemented properties (although I want readonly ones)
Jon Skeet
Readonly ones: {get; private set;} - and your sorted ;)
TWith2Sugars
readonly and a private set isn't the same thing
Daok
+9  A: 

I'll second the Python array accessors, and complement it with the List Comprehensions:

[x*x for x in range(10)]

and list unpacking:

(a,b) = (b,a)
Mr Shark
+5  A: 

Groovy:

  • Null-safe dereferencing (?.)
Jon Skeet
+1  A: 

Some very nice suggestions already, not exactly a language feature but one tool i use a lot within PHP is strtotime(), pretty handy to be able to just say "tomorrow", "next friday" or "+1 day 20 sec" and get unixtime as a result.

Ólafur Waage
+3  A: 

Objective-C

@property

Saves a lot of typing for simple setters and getters and are easily overwritten.

Abizern
+4  A: 
  • Method chaining
  • C# anonymous delegates for predicate list control
  • C# accessors
  • PHP arrays
  • ECMAScript for XML!!
kRON
+3  A: 

JavaScript;

.

Logical Operators: || and &&

var iWantTheTruth = truthyValue || falsyValue;

.

Closures:

Inner functions having access to the variables of their outer functions (even after the outer functions have returned!)

.

The array-like arguments object:

var add = function () {
    var sum = 0;
    for (var ic = 0; ic < arguments.length; ic += 1) {
        sum += parseInt(arguments[ic], 10);
    }
    return sum;
};
var total = add(1,5,2,6,3,4,3); //I can pass how many parameters i want

.

Functions as first-class objects :

var invoker = function (fnc) {
    if (typeof fnc === 'function') {
        fnc('my parameters');
    }
};

invoker(function (p) {
    alert('first parameter passed is : ' + p);
});
Andreas Grech
Is `fnd` a typo?
Svante
+4  A: 

Haskell's list comprehensions are my personal favorites.

[ x | x <- y, x > z]

Python has very similar constructs, but Haskell's are more compact. Haskell also allows multiple generators in the same comprehension, something which afaik is not possible in Python.

Lazy evaluation in Haskell is another amazing tool (if you can get your head around it). It makes implementing dynamic programming techniques much more straightforwards.

edit- Thinking back, another of my favorites is C's ternary operator:

result = condition ? true_statement : false_statement;

Again, python also has it in the form of the x if y else z construct, but I still prefer C's layout.

saffsd
It should be noted that most modern, C-based languages have that same ternary operator.
dancavallaro
Except Python, which can simulate a ternary operator, but has some wonderful gotchyas when trying to do so.
Josh Smeaton
+3  A: 

Clotures and lambdas in c#. I dunno what this smells like to other people, but to me it smells like win:

public void AMethodThatNormallyWouldRequireStoringStateInTheObjectScope()
{
  var victim = AnObjectLol();
  object result = null;

  victim.AnEventSignifyingWorkIsDone += (o,e) =>  result = e.Result;

  victim.AMethodThatFiresAnEventWhenDone(); // blocks until after the event fires

  SomeOtherMethod(result);
}

If you're not careful you can leak memory doing this. However, you can use this technique to avoid having to store result at the object level, which I think is a definite code smell...

Will
+1  A: 

I suppose it's controversial, but if you know how to use it, the preprocessor can be your automatic programmer. For example:

Mike Dunlavey
+1  A: 

perl (foreach $x in @array) type of loop.

plus the sort that you can add in the foreach, i just can't believe how easy is it to sort using perl :) foreach (sort $x in @array){}

or to reverse sort foreach (reverse sort $x in array)

or even to sort by case insensitive manner: foreach (sort {lc $a cmp lc $b $x} in @array){}

melaos
There is an extra $x in the last example.
Hudson
+3  A: 

I love lot of Lua's syntax sugar:

print"Foo" instead of print("Foo"); doStuff{ a, b } instead of doStuff({ a, b }) allowing syntax tricks like:

defineSomething
{
  stuff = 1
}

► The classical but always appreciated a, b = b, a and s, x, y = getResult(z)

And lot more.

► In Java, the new for iterator is nice. The flexibility of enum is good too.

PhiLho
don't forget the short and sweet `#blah` which gets the length of blah (assuming it's a table)
RCIX
+1  A: 

Java:

anonymous subclasses with instance initializer blocks:

Set<String> prefilledStringSet = new HashSet<String>() {{
    put("foo");
    put("bar");
    put("baz");
}};

combined with dynamic proxies to create little DSLs like jMock, so you can program your mocks using real method calls with an obvious syntax:

testObjectContext.checking(new Expectations(){{
    one(testObject).callTestMethod("hello"); will(returnValue("world"));
}});
Dan Vinton
A: 
joki
+3  A: 

Perl

The Schwartzian Transform.

This example:

my @sorted_by_length = 
  map  { $_->[0] }
  sort { $a->[1] <=> $b->[1] }
  map  { [ $_, length $_ ] }
       @strings;

maps an list of strings to a list of pairs of string and string length, then sorts the pairs by the second entry of the pair (i.e. the length), then maps the list of pairs back to the strings.

Edit: because the map to array, sort array, then map from array structure, the length function is guaranteed to only execute n times. This on average has a better performance than a single comparator method. /Edit

The trick is to read it backwards.

The bonus cool about it is that it's also known as "Black Magic", Randal Schwartz invented it, and Schwartz is German for black.

jamesh
Jules
+1  A: 
  1. Datatype? for Nullable datatype in C#
  2. while(++destination=++source) in C
  3. IsNot operator in VB.net
  4. Generics in any language
  5. 5|.times in Ruby
  6. Multicast delegate in .Net
Varun Mahajan
+1  A: 

In Java:

  • static imports
    • import static java.lang.System.out; ... out.println(); (not having the System. prefix just feels so much cleaner, and for java.lang.Math static methods too)
  • Generics, wee, let's not get spoiled and try to remember the times when we didn't have them, in those dark days.
Andrew Coleson
+1 Use the static imports in the same way as you do.
Helper Method
+1  A: 

Python's compound list comprehensions:

[x * y * z for x in range(3) for y in range(3) for z in range(3) if not (x * y * z) % 2 and x * y * z]

is syntactic sugar for:

lst = []
for x in range(3):
    for y in range(3):
        for z in range(3):
            if x * y * z > 0:
                if x * y * z % 2 == 0:
                    lst.append(x*y*z)
return lst
J.T. Hurley
+3  A: 

C++

const & - just brilliant.

C#

delegates - function pointers have never been easier. iterators - continuations can be very useful.

Perl

For quick'n'dirty programming it is really nice that you have sensible default (all the weird $-vars). I also like the fact that if can appear both before and after the statement it governs. This makes output with optional text a lot easier to read.

Brian Rasmussen
+1  A: 

I love the Lisp style boolean logic, which Python and JavaScript stole.

e.g.

(or abc xyz) ;; Lisp
abc || xyz   // JS/Python

Returns the first value which returns non-nil, rather than a boolean saying that one or the other did. To accomplish the same thing in C(-style languages), you'd need:

abc ? abc : xyz;
ieure
You can write x = abc || xyz in most c-style languages to get equivalent of x = abc ? abc : xyz. It's just not the popular idiom.
jmucchiello
+2  A: 

Common Lisp backtick notation.

David Thornley
A: 

Delphi: passing functions as parameters.

Type myFunc = function (Arg1: integer): boolean;

Function aFunction(i: integer):boolean;
begin
// do stuff
end;

Function aCaller(aFunc: myFunc; i: integer);
begin
if aFunc(i) then
 begin
 // do stuff
 end;
end;

begin
aCaller(aFunction, 10);
end.

Rob

RobS
A: 

QT's

forever {
}
Ronny
Is that really better than just about every other c-like language's while (1) {}?
jmucchiello
+1  A: 

C++ pointer to member.

Jared Updike
A: 

Im going with

  1. C++ templates
  2. Java Generics
  3. C# Generics
  4. Erlang List Comprehension
Signal9
+2  A: 

From most important to least:

  • Lisp-style macros
  • Some way to define generic operations (via OO dispach for example)
  • Lambda's
  • Pattern matching
  • Tail calls
  • Coroutines
Jules
A: 
  • Higher order functions
  • macros that can use the complete language to operate on the abstract syntax tree
  • s-expressions (works together with the previous point)
  • multiple dispatch for generic functions
  • three-tier condition system
Svante
A: 

I just can't stop loving Lua's tables. They can implement any and every data structure you could want while being zippy and nice! Add in metatables and you get read-only lists, default values, even objects...

True story: One of my programming friends drooled over what was essentially a C# implementation of lua tables! they are just that awesome...

RCIX
A: 

JavaFX if-else, which combines Java's if-else and ternary expression:

def num = 12;
def even = if (num mod 2 == 0) true else false;
Helper Method