views:

97

answers:

4

So the idea behind an array and a function are very similar from a black-box perspective. You pass in the input value(s) and retrieve the output value. So is it better to keep array syntax and function syntax the same or is it better to have differences?

e.g.

print array[0]

print func(0)

versus

print array(0)

print func(0)

+1  A: 

Technically you're right, they're both mappings, but in most programmers' minds there is a difference: arrays store their values while functions compute their values. In other words, (simplistically) arrays are optimized for speed, and functions are optimized for memory. I think that's a good distinction to maintain.

David Zaslavsky
A: 

Ruby does some conflation - methods use (), but arrays, hashes, and lambda expressions (closest thing that ruby has to functions) can all use []. Together with ducktyping, this means you can pass around an object, and pass it values using [] not caring whether it's precomputed (an array), calculated each time (a lambda expression), or calculated as needed and cached (which can be done with a hash).

Another example that conflates the two is Haskell. As I remember it doesn't have an array syntax built into the languange - accessing array indices is a function call, and can be used just like any other function.

I prefer conflation actually - it allows for easier flexibility (which I like). Knowing whether you're optimizing for speed or memory (like David said) is good to know, but I'm willing to take that responsibility on myself, rather than leaving it to cues built into the language.

rampion
A: 

Well, I think traditionally, this comes from the C/Algol syntax, where [] is directly translated into a memory offset, whereas () is a much more complicated procedure.

In some of the newer languages, [] is a generic indexing for primitive data structures, eg, hashes in Js are accessed via:

hash["Hello"];
array[0];

I think it's useful to keep "index" syntax different from "argument" syntax.

CookieOfFortune
A: 

You are absolutely right. Arrays, and also Maps and Dictionaries and arguably even Objects are essentially functions in the mathematical sense. And, indeed, there are languages, which treat Arrays as functions of integers, Maps and Dictionaries as functions of their keys and Objects as functions of their slots. Two of those languages are Scala and Clojure.

Jörg W Mittag