HACKER Q&A
📣 iamwil

How come there's a distinction between defining vs. calling a function?


In pure functional languages, like Haskell, a function with no arguments is treated as its result.

foo : Int foo = 1 + 1

Whereas in most other imperative languages, there's a distinction between defining a function, and calling the function. Example in javascript

// defining a function const foo = () => 1 + 1

// calling a function foo()

If you want to call a function right after defining it.

const foo = (() => 1 + 1)()

How come most languages make this distinction? The only thing I could think of is that it gives fine-grained control to programmer when something is executed. If it wasn't, then you'd have to rely on lazy evaluation.

Are there other reasons? Was it a historical accident?


  👤 jgwil2 Accepted Answer ✓
In pure functional languages a function is a mathematical function: each time it is invoked with the same input, you get the same output. Imperative "functions" are really procedures, that is to say, labels for a set of instructions to be executed. There are no limitations on what those instructions might do, including IO or accessing program state, so there is no way to know whether the result of their execution will be the same from one time to the next.

👤 carapace
Referential transparency

https://en.wikipedia.org/wiki/Referential_transparency

> Referential transparency and referential opacity are properties of parts of computer programs. An expression is called referentially transparent if it can be replaced with its corresponding value (and vice-versa) without changing the program's behavior.[1] This requires that the expression be pure, that is to say the expression value must be the same for the same inputs and its evaluation must have no side effects. An expression that is not referentially transparent is called referentially opaque.

> In mathematics all function applications are referentially transparent, by the definition of what constitutes a mathematical function. However, this is not always the case in programming, where the terms procedure and method are used to avoid misleading connotations. In functional programming only referentially transparent functions are considered. Some programming languages provide means to guarantee referential transparency. Some functional programming languages enforce referential transparency for all functions.


👤 Iceland_jack
foo is not a function, it's just a value. It cannot be applied, it does not have a function type (.. -> ..)