3

I'm talking mostly about functional programming languages. For example, the wikipedia article for map has this example in a Haskell-ish language:

map square [1,2,3,4,5]

How does the parser/compiler know that we want to pass the function square to map as a higher-order function, and not trying to invoke the function itself? For languages with static typing, the expression square [1,2,3,4,5] obviously wouldn't compile, but would a compiler really use that to determine that's not what I meant?

Or, is this just a bad example from Wikipedia, and a better example might look like map &square [1,2,3,4,5] (using C-style function referencing)?

hammar
  • 138,522
  • 17
  • 304
  • 385

3 Answers3

5

First of all function application has the highest precedence. so when the parser encounters "map" it will take the first thing to its right as the first argument. map type expects a function as first argument, and "square" is defined as a function, so types are compatible. You can think of map square as a function that is expecting a list of numbers.

The key is to examine types, and verify arguments types, following precedence rules.

martincho
  • 4,517
  • 7
  • 32
  • 42
  • 2
    @user793587: Note also that, in normal circumstances, everything in Haskell is roughly a reference to an immutable value (or a suspended computation to produce such a value). So you can think of both `map` and `square` as being "references" in the C sense. Combined with the parsing rule (keeping in mind that whitespace indicates function application), that should make things clear. – C. A. McCann Aug 24 '11 at 04:14
  • But there is a space after `square`, yet that function is not applied (directly). –  Aug 25 '11 at 04:15
4

It's just a matter of parsing: function application in Haskell is left-associative, so map square [1, 2, 3, 4, 5] is parsed as ((map square) [1, 2, 3, 4, 5]) rather than (map (square [1, 2, 3, 4, 5])).

Wyzard
  • 33,849
  • 3
  • 67
  • 87
0

It depends on the language.

In Javascript, for example, you can reference a function f by simply not putting parentheses after it.

Here, f is treated as function pointer.

map(f, [1,2,3,4,5]);

Here, it is treated as a function call:

f([1,2,3,4,5]);

In Scala, the rules are quite a bit more complex, and the compiler has some leeway in "guessing" whether or not you're invoking or referring to the function. See What is the rule for parenthesis in Scala method invocation? for a more detailed explanation.

Community
  • 1
  • 1
Nick
  • 572
  • 3
  • 9