
Strangest language feature - tszming
http://stackoverflow.com/questions/1995113/
======
silentbicycle
I'm a bit disappointed in this discussion. "strangest" language feature sounds
like a crowd pointing and laughing. Boring! What are some novel,
underappreciated, unexpectedly useful language features? (And this
emphatically isn't about "my favorite language vs yours".)

Here are a couple, to get things rolling.

Pattern matching. This is a favorite of mine - stating what you want (or
expect), possibly with variables, and letting the language generate the tree
of if/case statements. I find pattern-matching code extremely easy to read,
easy to extend, almost always right the first time, etc. It works with both
static (ML-style variant types, reminding you to check exhaustively) and
dynamic (Erlang-style, "handle what you can or throw an exception") typing.
awk is based around a weaker form of pattern matching (only matching against
ints and regexes, rather than whole trees), and it's still great for quick
hacks. PM seems to mesh poorly with conventional OO, though.

Compile-time metaprogramming. This is HN, you've probably heard plenty about
Lisp macros, so I'll leave it at that.

Incremental development / hot code loading. Erlang has this (with soft real-
time guarantees), Lisp, Smalltalk, and basically anything image-based has had
this for ages. It's often easier to grow a system piece by piece than to build
it upfront and plug in together afterward.

Iterators/generators. Without needing a fully lazy-by-default language such as
Haskell, it's often handy to have a handle into a (possibly infinite) stream
that you can pull from as necessary. Prolog combines pattern matching
(unification really, a step beyond pattern matching) with backtracking, so you
can write "generate and test" code: "here's what I want, this generates a
stream of all possible candidates, here's how to narrow it down". It's
sometimes too slow for use in production (due to combinatorial blowups), but
it's _excellent_ for prototyping, and can usually be made good enough with
some tweaks.

Coroutines and actors. Like iterators and generators, but breaking the flow of
execution into lots of little autonomous pieces. Communication makes dataflow
explicit, most things can be easily understood in isolation, and they can
often be run in parallel. (Coroutines are cooperative.)

~~~
kanak
To this excellent list I'd add:

First Class Continuations like in Scheme.

~~~
silentbicycle
What other languages have first class continuations? Scheme does, some SML
implementations do (smlnj has call/cc, IIRC), Ruby has call/cc* , anything
else?

* But I've heard it's _really_ not implemented for performance, and probably doesn't get used that much. I'm not really into Ruby, so...anyone?

Of course, you can do CPS yourself, though realistically you need first-class
functions, tail-call optimization, and garbage collection or the extra
bookkeeping will make it overwhelmingly complicated.

------
Groxx
Gotta read through a bit, but there are some excellent ones in there. Personal
favorite with C++ templates:

    
    
      assert( ( o-------------o
                |L             \
                | L             \
                |  L             \
                |   o-------------o
                |   !             !
                !   !             !
                o   |             !
                 L  |             !
                  L |             !
                   L|             !
                    o-------------o ).volume == ( o-------------o
                                                  |             !
                                                  !             !
                                                  !             !
                                                  o-------------o ).area * int(I-------------I) );
    

[http://stackoverflow.com/questions/1995113/strangest-
languag...](http://stackoverflow.com/questions/1995113/strangest-language-
feature/2024573#2024573)

------
halo
I was disappointed after clicking the link, because from the title, it sounded
like it would be an insightful list of unusual useful features, but instead
it's mostly a boring list of language design bugs or quirks.

------
arethuza
The video of implementing Conway's Game of Life in APL is awesome:

<http://www.youtube.com/watch?v=a9xAKttWgP4>

~~~
ww520
I'm curious. How come no one claim APL being expressive?

~~~
lukev
To be usefully expressive, a language must not only be compact, but easy to
read.

From what I've seen, APL is pretty much a write-only language. Code can't be
read, only deciphered.

~~~
regularfry
There's a trick to it. I was reading Ken Iverson's Notation as a Tool of
Thought paper (look it up, it's worth a read) which is basically a whistlestop
introduction to APL. I realised that it's very difficult (for me) to reason
about when I read it left to right, but it's almost trivial read right to
left.

That's right, it's a language that makes more sense backwards than it does
forwards.

~~~
raganwald
<http://www.jsoftware.com/papers/tot.htm>

------
ratsbane
Dynamic scope. Not really very strange but very unusual; not supported by many
languages. AFAIK Perl and Lisp(ish) languages are the only ones. For example:

    
    
      sub foo {my $x='fish'; local $y='chips'; &bar;}
    
      sub bar {print "\$x is >$x< and \$y is >$y<\n";}
    

This will output

    
    
      $x is >< and $y is >chips<
    

It's quite handy - saves passing around a "context" object, for example. The
remarkable thing is how few languages implement some form of it.

~~~
btilly
Dynamic scope is supported in older Lisps (eLisp is the only widely used
variant with it), and a variety of scripting languages including PHP, Perl,
TCL and vimsh (that's vim's internal scripting language). It is rarish because
it has been recognized as a bad design, but it still turns up because it is
easy to implement.

~~~
bretthoerner
> eLisp is the only widely used variant with it

I think you mean it's the only widely used variant where it's the default.
It's available in CL and Clojure when you want (need?) it.

~~~
jrockway
And Haskell:

    
    
       import Control.Monad.Reader
    
        type Action = ReaderT String IO ()
    
        foo :: Action
        foo = do
          bar
          local (const "new state") bar
          bar
    
        bar :: Action
        bar = liftIO . putStrLn =<< ask
    
        > runReaderT foo "foo"
        foo
        new state
        foo

------
famousactress
I can't say I'm surprised that three of the top 5 features on the post are
Javascript :|

~~~
vog
It is because the ECMAScript type system is a real WTF.

I always found the type system of PHP questionable, especially the useless and
bug provoking unity between arrays and hash tables. However, ECMAScript
provides such mis-design at an even lower level of the language. Nevertheless,
I still like working with ECMAScript because at least it has proper closures.

------
jperras
The strangest language 'feature' I've come across must be 'ticks' in PHP:

> A tick is an event that occurs for every N low-level tickable statements
> executed by the parser within the declare block. The value for N is
> specified using ticks=N within the declare blocks's directive section.

( <http://www.php.net/manual/en/control-structures.declare.php> )

PHP is a hodgepodge of inconsistent APIs and general weirdness already, but I
really did sit back and have a good WTF moment when I discovered this
'feature'. I have yet to encounter many people who have ever heard of ticks,
let alone anyone who has actually implement functionality that depended on
them. I've never seen something like that in Python or Ruby.

~~~
silentbicycle
It's really not that strange - it's probably intended debugging & profiling
code. It sounds like Lua's debugging hook
(<http://www.lua.org/manual/5.1/manual.html#lua_sethook>), which can run a
callback every N vm instructions.

I made a simple profiler by setting the hook to run every X ticks (typically
10,000), recording the call stack, and then seeing where most of the execution
happens. If every other time you look at the vm, it's in the same place, then
it's clearly a hotspot.

I don't know of an equivalent in Python or Ruby, off the top of my head, but
I'd be surprised if they weren't available.

------
btilly
My favorite examples from Perl. The reset function. The dump function. And the
fact that pos($x) = pos($x) is _NOT_ a no-op. (It clears an internal flag
allowing a zero-length regular expression to match again. Yes, I've used
this.)

Another fun one is that in Perl that local can operate on data structures. As
in local $foo{bar}. (I use this every so often in recursion sanity checks. But
it is still an odd feature.)

------
profquail
Awesome comment on trigraphs in C:

 _These let you use the "WTF operator":_

    
    
      (foo() != ERROR)??!??! cerr << "Error occurred" << endl;

~~~
tome
[Language pedant: although it's legal C, the use of cerr and endl and << is
more likely to occur in C++!]

~~~
senki
<< is C++ only.

~~~
tome
<< is the left-shift operator in C, so the OP's code _is_ syntactically valid
C.

It ought not to compile though, since it's trying to shift cerr by a string!

~~~
senki
Thanks. Sorry. I'm stupid...

------
samratjp
It amazes me how so many times this python feature gets overlooked:

    
    
        >>> x=5
        >>> 1<x<10
        True
        >>> 1<x<3
        False
    

_EDIT: fixed spaces, thanks epochwolf for the indent tip._

~~~
judofyr
If anyone is interested, here's how you could implement it in Ruby:
<http://judofyr.net/posts/chained-comparisons.html>

------
defen
How is call/cc not on there...don't tell me your mind wasn't blown when you
learned about that one.

------
j_baker
I'd have to say intercal's COMEFROM: <http://en.wikipedia.org/wiki/COME_FROM>

------
gamache
Perl will convert from base 26 to base 10 if you know how to ask:

    
    
      $ perl -E 'say lc (@a="a".."asdf")'
      30530

~~~
ralph
Base 26 or 36? Is 'a' 0 or 10? Does 's' overflow to the next column, like 09
in octal?

------
regularfry
It's interesting how many of these that aren't outright misfeatures are
recognisable as half-implemented Common Lisp features if you squint at them
sideways: Python's comparison chains, bc's quit/halt difference, VB7's Loop,
JS's multiple-value return, SFINAE in C++... I'm sure there are others.

~~~
omaranto
I mostly agree but in the case of comparison chains it is lisp that has the
half-implemented version: of course a<b<c is (< a b c), but a<=b<c, which is
actually more common in my code, becomes (and (<= a b) (< b c)).

Mathematica, which has much in common with lisp, does something analogous to
(inequalities a '<= b '< c), using symbols for the comparisons.

------
protomyth
Icon conditions were pretty interesting.

------
lectrick
I am happy to not see Ruby represented here.

~~~
judofyr
Just on the top of my head:

1\. The flip-flop

    
    
        >> s = true
        >> (1..10).reject { true if (s = !s) .. (s) }
        => [1, 3, 5, 7, 9]
    

2\. A snake in my Ruby?!?

    
    
        # Works in both Python and Ruby
        print """Hello World"""
    

3\. END vs at_exit

    
    
        END {
          puts "Ruby has END ..."
        }
    
        at_exit do
          puts "... and at_exit"
        end
    
        puts "Do you know the difference?"
    

4\. BEGIN/END wtf?

    
    
        # Have you ever seen these in production code?
        BEGIN {}
        END {}
    

5\. The wonders of a single space

    
    
        # Returns the position where the regexp matches "foobar",
        # or nil if no match.
        def get(regexp = /bar/)
          regexp =~ "foobar"
        end
    
        get /1#/   # => nil
        get / 1#/  # => 3    <- WTF?
    

6\. Local variable tables; don't we all love them?

    
    
        def get(regexp = /bar/)
          regexp =~ "foobar"
        end
    
        get /1#/   # => nil
        get = 5
        get /1#/   # => 5
        get / 1#/  # => 5

~~~
derefr
Just guessing that your #4, BEGIN and END, are for using Ruby like awk (that
is, from the shell—you should never see them in a script.) Try this (and
cringe):

    
    
        cat /usr/share/dict/words | ruby -lne 'puts $_.reverse; n = (n || 0) + 1; END{ puts "total: #{ n }" }'

------
mkramlich
For me it was strange that Ruby used "end" as the block ending delimiter in a
world and era where so many other languages were using "}" quite effectively,
thank you very much. And Python was showing you didn't even need that much. It
felt like a throwback to an earlier era of programming, like COBOL or Pascal.

~~~
yxhuvud
There are a lot stranger stuff hiding in Ruby.

Flip-flops. Do I need to elaborate?

~~~
avar
Ruby got its flip-flop operator from Perl, which in turn got it from sed and
awk. It can be really useful for keeping simple state, e.g.:

    
    
        # parse mail messages
        while (<$email>) {
            $in_header =   1  .. /^$/;
            $in_body   = /^$/ .. eof;
            if ($in_header) {
                # do something
            } else { # in body
                # do something else
            }
        }
    
    

And other examples at <http://perldoc.perl.org/perlop.html#Range-Operators>

