why aren't anonymous functions in Lua expressions? - function

Can anyone explain to me why the anonymous function construct in Lua isn't a fully fledged expression? To me this seems an oddity: it goes (slightly) against the idea that functions should be first class objects, and is (not often but occasionally) an inconvenience in what is mostly a really well-thought out and elegant language.
example, using the command line Lua, with workaround
Lua 5.3.3 Copyright (C) 1994-2016 Lua.org, PUC-Rio
> function(x) return x*x end (2)
stdin:1: <name> expected near '('
> square = function(x) return x*x end
> square(2)
4

Lua's function call syntax has some syntactic sugar built into it. You can call functions with 3 things:
A parenthesized list of values.
A table constructor (the function will take the table as a single argument).
A string literal.
Lua wants to be somewhat regular in its grammar. So if there's a thing which you can call as a function in one of these ways, then it should make sense to be able to call it in any of these ways.
Consider the following code:
local value = function(args)
--does some stuff
end "I'm a literal" .. foo
If we allow arbitrary, unparenthesized expressions to be called just like any other function call, then this means to create a function, invoke it with the string literal, concatenate the result of that function call with foo, and store that in value.
But... do we actually want that to work? That is, do we want people to be able to write that and have it be valid Lua code?
If such code is considered unsightly or confusing, then there are a few options.
Lua could just not have function calls with string literals. You're only saving 2 parentheses, after all. Maybe even don't allow table constructors as well, though those are less unsightly and far less confusing. Make everyone use parentheses for all function calls.
Lua could make it so that only in the cases of lambdas are function calls with string literals prevented. This would require substantially de-regularizing the grammar.
Lua could force you to parenthesize any construct where calling a function is not an obviously intended result of the preceding text.
Now, one might argue that table_name[var_name] "literal" is already rather confusing as to what is going on. But again, preventing that specifically would require de-regularizing the grammar. You'd have to add in all of these special cases where something like name "literal" is a function call but name.name "literal" is not. So option 2 is out.
The ability to call a function with a string literal is hardly limited to Lua. JavaScript can do it, but you have to use a specific literal syntax to get it. Plus, being able to type require "module_name" feels like a good idea. Since such calls are considered an important piece of syntactic sugar, supported by several languages, option #1 is out.
So your only option is #3: make people parenthesize expressions that they want to call.

Oh I see.. round brackets are needed, sorry.
(function(x) return x*x end) (2)
I still don't see why it is designed like that.

Short Answer
To call a function, the function expression must be either a name, an indexed value, another function call, or an expression inside parentheses.
Long Answer
I don't know why it's designed that way, but I did look up the grammar to see exactly how it works. Here's the entry for a function call:
functioncall ::= prefixexp args | prefixexp ‘:’ Name args
"args" is just a list of arguments in parentheses. The relevant part is "prefixexp".
prefixexp ::= var | functioncall | ‘(’ exp ‘)’
Ok, so we can call another "functioncall". "exp" is just a normal expression:
exp ::= nil | false | true | Numeral | LiteralString | ‘...’ | functiondef | prefixexp | tableconstructor | exp binop exp | unop exp
So we can call any expression as long as it's inside parentheses. "functiondef" covers anonymous functions:
functiondef ::= function funcbody
funcbody ::= ‘(’ [parlist] ‘)’ block end
So an anonymous function is an "exp", but not a "prefixexp", so we do need parentheses around it.
What is "var"?
var ::= Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name
"var" is either a name or an indexed value (usually a table). Note that the indexed value must be a "prefixexp", which means a string literal or table constructor must be in parentheses before we can index them.
To sum up: A called function must be either a name, an indexed value, a function call, or some other expression inside parentheses.
The big question is: Why is "prefixexp" treated differently from "exp"? I don't know. I suspect it has something to do with keeping function calls and indexing outside the normal operator precedence, but I don't know why that's necessary.

Related

Clojure Function check

When i have 3 functions in a program, how do i check a specific function name ?
I want to know the name of those function for the sake of function selection.
Let say linear-kernel function, logistic-kernel function, and non-negative function, when i call the program, one of those function is called and i should to check whether it was linear, logistic or non-negative function, so i can execute another function related with the selected function.
I think doing function selection will save my time from repeating the base code. But doing function selection maybe is not the best design that i could use in Clojure.
FYI, at this level, i already use the "meta" keyword to access the function name, but when i create
(defn isKernel [krn]
(if (= (str (:name (meta #'krn))) "logistic-kernel") 1 0))
The compiler cannot resolve the 'krn' var
In Clojure functions are values, just like the number 4. This is a big part of the underpinnings of much of the language (and functional programming in general). Most of the time we store functions in vars though this is not required. functions as values don't have names* So rather than checking to see if the name of a passed function matches a known name, it makes more sense to ask "does this function have the same value as the function stored in the var" as #cgrand points out this can be accomplished simply by calling =.
If you are doing this kind of dispatch there is a good change that protocols are a better tool than rolling your own
*they do have names for the purpose of creating recursive function literals though thats not what I'm getting at here.

In Lua, what is the difference between functions that use ":" and functions that do not? [duplicate]

This question already has answers here:
Difference between . and : in Lua
(3 answers)
Closed 7 years ago.
Let's say we have two function declarations:
function MyData:New
end
and
function New(MyData)
end
What is the difference between them? Does using : have any special purpose when it comes to inheritance and OOP? Can I only call functions declared with : by using :?
I'm coming from using only C# -- so if there's any comparison to be made, what would it be?
Adapted from the manual, end of §3.4.10:
The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter self. Thus, the statement
function t:f (params) body end
is syntactic sugar for
t.f = function (self, params) body end
You should search SO as there are many questions about this but you have a set of questions so I can't say this is a duplicate.
Q. What is the difference between them?
A. The one with colon causes a method to be added to the MyData table, and the Lua interpreter to automatically insert a "self" before the first parameter when called, with this "self" pointing to the MyData instance that the "method" is being called upon. It is the same as writing MyData.New = function(self) end. The second signature has a parameter called MyData and is a global function. It is unrelated to the MyData table (or class).
Q. Does using ":" have any special purpose when it comes to inheritance and OOP?
A. No; it is merely syntactic sugar so that when you call MyData.New you can just write MyData:New() instead of the clunky looking MyData.New(MyData). Note that a "new" function is typically to create instances of a class, so you wouldn't have such a function be a method, rather just a function in the MyData table. For inheritence and OOP, you use metatables, and this does not interact with : in any special way.
Q. Can I only call functions declared with ":" by using ":"?
A. No, as mentioned, it just syntactic sugar, you can define one way and call a different way.
Q. I'm coming from using only C# -- so if there's any comparison to be made, what would it be?
A. For functions, the : is like the . in C#, whether used in a call or definition. The "." in Lua is more like "attribute", there is no equivalent in C# for functions.
MyData = {} -- a table
function MyData.func(self)
print('hello')
end
MyData:func()
MyData.func(MyData) -- same as previous
function MyData:func2() -- self is implicit
print('hello')
end
MyData:func2()
MyData.func2(MyData) -- same as previous
Note that MyData as defined above is not a class, because you cannot create "instances" of it (without doing extra work not shown there). Definitely read the Programming in Lua online book on the Lua.org website, lots of useful discussions of these notions.
Lua doesn't have functions declarations per se; It has function definition expressions. The syntax you have used is shorthand for a function definition expression and assignment.
The only difference in your examples is when the first statement is executed a new function is created and assigned to the field New in the table referenced by the variable MyData, whereas the second is an assignment to a non-field variable (local, if previously declared, otherwise global).
Keep in mind that these are only the first references to the created function values. Like any other value, you can assign references to functions to any variable and pass them as parameters.
If you add formal parameter usage to the bodies then there is another difference: The first has an implicit first parameter named self.
If you add function calling to the scenarios, the ":" syntax is used with an expression on the left. It should reference a table. The identifier to the right should be a field in that table and it should reference a function. The value of the left expression is passed as the first actual argument to the function with any additional arguments following it.
A function definition with a ":" is called a method. A function call with a ":" is called a method call. You can construct a function call to a function value that is a field in a table with the first argument being a reference to the table using any function call syntax you wish. The Lua method definition and method call syntax makes it easier, as if the function was an instance method. In this way, a Lua method is like a C# Extension Method.

How to define my function from a string?

This is normal definition of some function as I know:
real function f(x)
real x
f = (sin(x))**2*exp(-x)
end function f
But I want to define a function from some string, for example the program will ask me to write it, and then it will define the function f in a program. Is this possible in Fortran?
What you are looking for is possible in reflective programming languages, and is not possible in Fortran.
Quote from the link above:
A language supporting reflection provides a number of features available at runtime that would otherwise be very obscure to accomplish in a lower-level language. Some of these features are the abilities to:
Discover and modify source code constructions (such as code blocks, classes, methods, protocols, etc.) as a first-class object at runtime.
Convert a string matching the symbolic name of a class or function into a reference to or invocation of that class or function.
Evaluate a string as if it were a source code statement at runtime.
Create a new interpreter for the language's bytecode to give a new meaning or purpose for a programming construct.
I worked on a project once that tried to achieve something similar. We read in a string that contained a string with named variables and mathematical operations (a function if you will). In this string the variables then got replaced by their numerical values and the terms were evaluated.
The basic idea is not to too difficult, but it requires a lot of string manipulations - and it is not a function in the context of a programming language.
We did it like this:
Recursively divide the string at +,-,/,*, but remember to honor brackets
If this is not possible (without violating bracketing), evaluate the remaining string:
Does it contain a mathematical expression like cos? Yes => recurse into arguments
No => evaluate the mathematical expression (no variables allowed, but they got replaced)
This works quite well, but it requires:
Splitting strings
Matching in strings
Replacing strings with other strings, etc.
This is not trivial to do in Fortran, so if you have other options (like calling an external tool/script that returns the value), I would look into that - especially if you are new to Fortran!

Functions in Lua

I am starting to learn Lua from Programming in Lua (2nd edition) I didn't understand the following in the book.
network = {
{name ="grauna", IP="210.26.30.34"},
{name ="araial", IP="210.26.30.23"},
}
If we want to sort the table by field name, the author mentions
table.sort(network, function (a,b) return (a.name > b.name) end }
Whats happening here? What does function (a,b) stand for? Is function a key word or something.
If was playing around with it and created a table order
order={x=1,x=22,x=10} // not sure this is legal
and then did
print (table.sort(order,function(a,b) return (a.x > b.x) end))
I did not get any output. Where am I going wrong?
Thanks
It's an anonymous function that takes two arguments and returns true if the first argument is less than the second argument. table.sort() runs this function for each of the elements that need sorting and compares each element with the previous element.
I think (but I am not sure) that order={x=1,x=22,x=10} has the same meaning in Lua as order={x=10}, a table with one key "x" associated with the value 10. Maybe you meant {{x=1},{x=22},{x=10}} to make an "array" of 3 components, each having the key "x".
To answer the second part of your question: Lua is very small, and doesn't provide a way to print a table directly. If you use a table as a list or array, you can do this:
print(unpack(some_table))
unpack({1, 2, 3}) returns 1, 2, 3. A very useful function.
function in lua is a keyword, similar to lambda in Scheme or Common Lisp (& also Python), or fun in Ocaml, to introduce anonymous functions with closed variables, i.e. closures

Expression Versus Statement

I'm asking with regards to c#, but I assume its the same in most other languages.
Does anyone have a good definition of expressions and statements and what the differences are?
Expression: Something which evaluates to a value. Example: 1+2/x
Statement: A line of code which does something. Example: GOTO 100
In the earliest general-purpose programming languages, like FORTRAN, the distinction was crystal-clear. In FORTRAN, a statement was one unit of execution, a thing that you did. The only reason it wasn't called a "line" was because sometimes it spanned multiple lines. An expression on its own couldn't do anything... you had to assign it to a variable.
1 + 2 / X
is an error in FORTRAN, because it doesn't do anything. You had to do something with that expression:
X = 1 + 2 / X
FORTRAN didn't have a grammar as we know it today—that idea was invented, along with Backus-Naur Form (BNF), as part of the definition of Algol-60. At that point the semantic distinction ("have a value" versus "do something") was enshrined in syntax: one kind of phrase was an expression, and another was a statement, and the parser could tell them apart.
Designers of later languages blurred the distinction: they allowed syntactic expressions to do things, and they allowed syntactic statements that had values.
The earliest popular language example that still survives is C. The designers of C realized that no harm was done if you were allowed to evaluate an expression and throw away the result. In C, every syntactic expression can be a made into a statement just by tacking a semicolon along the end:
1 + 2 / x;
is a totally legit statement even though absolutely nothing will happen. Similarly, in C, an expression can have side-effects—it can change something.
1 + 2 / callfunc(12);
because callfunc might just do something useful.
Once you allow any expression to be a statement, you might as well allow the assignment operator (=) inside expressions. That's why C lets you do things like
callfunc(x = 2);
This evaluates the expression x = 2 (assigning the value of 2 to x) and then passes that (the 2) to the function callfunc.
This blurring of expressions and statements occurs in all the C-derivatives (C, C++, C#, and Java), which still have some statements (like while) but which allow almost any expression to be used as a statement (in C# only assignment, call, increment, and decrement expressions may be used as statements; see Scott Wisniewski's answer).
Having two "syntactic categories" (which is the technical name for the sort of thing statements and expressions are) can lead to duplication of effort. For example, C has two forms of conditional, the statement form
if (E) S1; else S2;
and the expression form
E ? E1 : E2
And sometimes people want duplication that isn't there: in standard C, for example, only a statement can declare a new local variable—but this ability is useful enough that the
GNU C compiler provides a GNU extension that enables an expression to declare a local variable as well.
Designers of other languages didn't like this kind of duplication, and they saw early on that if expressions can have side effects as well as values, then the syntactic distinction between statements and expressions is not all that useful—so they got rid of it. Haskell, Icon, Lisp, and ML are all languages that don't have syntactic statements—they only have expressions. Even the class structured looping and conditional forms are considered expressions, and they have values—but not very interesting ones.
an expression is anything that yields a value: 2 + 2
a statement is one of the basic "blocks" of program execution.
Note that in C, "=" is actually an operator, which does two things:
returns the value of the right hand subexpression.
copies the value of the right hand subexpression into the variable on the left hand side.
Here's an extract from the ANSI C grammar. You can see that C doesn't have many different kinds of statements... the majority of statements in a program are expression statements, i.e. an expression with a semicolon at the end.
statement
: labeled_statement
| compound_statement
| expression_statement
| selection_statement
| iteration_statement
| jump_statement
;
expression_statement
: ';'
| expression ';'
;
http://www.lysator.liu.se/c/ANSI-C-grammar-y.html
An expression is something that returns a value, whereas a statement does not.
For examples:
1 + 2 * 4 * foo.bar() //Expression
foo.voidFunc(1); //Statement
The Big Deal between the two is that you can chain expressions together, whereas statements cannot be chained.
You can find this on wikipedia, but expressions are evaluated to some value, while statements have no evaluated value.
Thus, expressions can be used in statements, but not the other way around.
Note that some languages (such as Lisp, and I believe Ruby, and many others) do not differentiate statement vs expression... in such languages, everything is an expression and can be chained with other expressions.
For an explanation of important differences in composability (chainability) of expressions vs statements, my favorite reference is John Backus's Turing award paper, Can programming be liberated from the von Neumann style?.
Imperative languages (Fortran, C, Java, ...) emphasize statements for structuring programs, and have expressions as a sort of after-thought. Functional languages emphasize expressions. Purely functional languages have such powerful expressions than statements can be eliminated altogether.
Expressions can be evaluated to get a value, whereas statements don't return a value (they're of type void).
Function call expressions can also be considered statements of course, but unless the execution environment has a special built-in variable to hold the returned value, there is no way to retrieve it.
Statement-oriented languages require all procedures to be a list of statements. Expression-oriented languages, which is probably all functional languages, are lists of expressions, or in tha case of LISP, one long S-expression that represents a list of expressions.
Although both types can be composed, most expressions can be composed arbitrarily as long as the types match up. Each type of statement has its own way of composing other statements, if they can do that all. Foreach and if statements require either a single statment or that all subordinate statements go in a statement block, one after another, unless the substatements allow for thier own substatements.
Statements can also include expressions, where an expression doesn't really include any statements. One exception, though, would be a lambda expression, which represents a function, and so can include anything a function can iclude unless the language only allows for limited lambdas, like Python's single-expression lambdas.
In an expression-based language, all you need is a single expression for a function since all control structures return a value (a lot of them return NIL). There's no need for a return statement since the last-evaluated expression in the function is the return value.
Simply: an expression evaluates to a value, a statement doesn't.
Some things about expression based languages:
Most important: Everything returns an value
There is no difference between curly brackets and braces for delimiting code blocks and expressions, since everything is an expression. This doesn't prevent lexical scoping though: A local variable could be defined for the expression in which its definition is contained and all statements contained within that, for example.
In an expression based language, everything returns a value. This can be a bit strange at first -- What does (FOR i = 1 TO 10 DO (print i)) return?
Some simple examples:
(1) returns 1
(1 + 1) returns 2
(1 == 1) returns TRUE
(1 == 2) returns FALSE
(IF 1 == 1 THEN 10 ELSE 5) returns 10
(IF 1 == 2 THEN 10 ELSE 5) returns 5
A couple more complex examples:
Some things, such as some function calls, don't really have a meaningful value to return (Things that only produce side effects?). Calling OpenADoor(), FlushTheToilet() or TwiddleYourThumbs() will return some sort of mundane value, such as OK, Done, or Success.
When multiple unlinked expressions are evaluated within one larger expression, the value of the last thing evaluated in the large expression becomes the value of the large expression. To take the example of (FOR i = 1 TO 10 DO (print i)), the value of the for loop is "10", it causes the (print i) expression to be evaluated 10 times, each time returning i as a string. The final time through returns 10, our final answer
It often requires a slight change of mindset to get the most out of an expression based language, since the fact that everything is an expression makes it possible to 'inline' a lot of things
As a quick example:
FOR i = 1 to (IF MyString == "Hello, World!" THEN 10 ELSE 5) DO
(
LotsOfCode
)
is a perfectly valid replacement for the non expression-based
IF MyString == "Hello, World!" THEN TempVar = 10 ELSE TempVar = 5
FOR i = 1 TO TempVar DO
(
LotsOfCode
)
In some cases, the layout that expression-based code permits feels much more natural to me
Of course, this can lead to madness. As part of a hobby project in an expression-based scripting language called MaxScript, I managed to come up with this monster line
IF FindSectionStart "rigidifiers" != 0 THEN FOR i = 1 TO (local rigidifier_array = (FOR i = (local NodeStart = FindsectionStart "rigidifiers" + 1) TO (FindSectionEnd(NodeStart) - 1) collect full_array[i])).count DO
(
LotsOfCode
)
I am not really satisfied with any of the answers here. I looked at the grammar for C++ (ISO 2008). However maybe for the sake of didactics and programming the answers might suffice to distinguish the two elements (reality looks more complicated though).
A statement consists of zero or more expressions, but can also be other language concepts. This is the Extended Backus Naur form for the grammar (excerpt for statement):
statement:
labeled-statement
expression-statement <-- can be zero or more expressions
compound-statement
selection-statement
iteration-statement
jump-statement
declaration-statement
try-block
We can see the other concepts that are considered statements in C++.
expression-statements is self-explaining (a statement can consist of zero or more expressions, read the grammar carefully, it's tricky)
case for example is a labeled-statement
selection-statements are if if/else, case
iteration-statements are while, do...while, for (...)
jump-statements are break, continue, return (can return expression), goto
declaration-statement is the set of declarations
try-block is statement representing try/catch blocks
and there might be some more down the grammar
This is an excerpt showing the expressions part:
expression:
assignment-expression
expression "," assignment-expression
assignment-expression:
conditional-expression
logical-or-expression assignment-operator initializer-clause
throw-expression
expressions are or contain often assignments
conditional-expression (sounds misleading) refers to usage of the operators (+, -, *, /, &, |, &&, ||, ...)
throw-expression - uh? the throw clause is an expression too
The de-facto basis of these concepts is:
Expressions: A syntactic category whose instance can be evaluated to a value.
Statement: A syntactic category whose instance may be involved with evaluations of an expression and the resulted value of the evaluation (if any) is not guaranteed available.
Besides to the very initial context for FORTRAN in the early decades, both definitions of expressions and statements in the accepted answer are obviously wrong:
Expressions can be unvaluated operands. Values are never produced from them.
Subexpressions in non-strict evaluations can be definitely unevaluated.
Most C-like languages have the so-called short-circuit evaluation rules to conditionally skip some subexpression evaluations not change the final result in spite of the side effects.
C and some C-like languages have the notion of unevaluated operand which may be even normatively defined in the language specification. Such constructs are used to avoid the evaluations definitely, so the remained context information (e.g. types or alignment requirements) can be statically distinguished without changing the behavior after the program translation.
For example, an expression used as the operand of the sizeof operator is never evaluated.
Statements have nothing to do with line constructs. They can do something more than expressions, depending on the language specifications.
Modern Fortran, as the direct descendant of the old FORTRAN, has concepts of executable statements and nonexecutable statements.
Similarly, C++ defines declarations as the top-level subcategory of a translation unit. A declaration in C++ is a statement. (This is not true in C.) There are also expression-statements like Fortran's executable statements.
To the interest of the comparison with expressions, only the "executable" statements matter. But you can't ignore the fact that statements are already generalized to be constructs forming the translation units in such imperative languages. So, as you can see, the definitions of the category vary a lot. The (probably) only remained common property preserved among these languages is that statements are expected to be interpreted in the lexical order (for most users, left-to-right and top-to-bottom).
(BTW, I want to add [citation needed] to that answer concerning materials about C because I can't recall whether DMR has such opinions. It seems not, otherwise there should be no reasons to preserve the functionality duplication in the design of C: notably, the comma operator vs. the statements.)
(The following rationale is not the direct response to the original question, but I feel it necessary to clarify something already answered here.)
Nevertheless, it is doubtful that we need a specific category of "statements" in general-purpose programming languages:
Statements are not guaranteed to have more semantic capabilities over expressions in usual designs.
Many languages have already successfully abandon the notion of statements to get clean, neat and consistent overall designs.
In such languages, expressions can do everything old-style statements can do: just drop the unused results when the expressions are evaluated, either by leaving the results explicitly unspecified (e.g. in RnRS Scheme), or having a special value (as a value of a unit type) not producible from normal expression evaluations.
The lexical order rules of evaluation of expressions can be replaced by explicit sequence control operator (e.g. begin in Scheme) or syntactic sugar of monadic structures.
The lexical order rules of other kinds of "statements" can be derived as syntactic extensions (using hygienic macros, for example) to get the similar syntactic functionality. (And it can actually do more.)
On the contrary, statements cannot have such conventional rules, because they don't compose on evaluation: there is just no such common notion of "substatement evaluation". (Even if any, I doubt there can be something much more than copy and paste from existed rules of evaluation of expressions.)
Typically, languages preserving statements will also have expressions to express computations, and there is a top-level subcategory of the statements preserved to expression evaluations for that subcategory. For example, C++ has the so-called expression-statement as the subcategory, and uses the discarded-value expression evaluation rules to specify the general cases of full-expression evaluations in such context. Some languages like C# chooses to refine the contexts to simplify the use cases, but it bloats the specification more.
For users of programming languages, the significance of statements may confuse them further.
The separation of rules of expressions and statements in the languages requires more effort to learn a language.
The naive lexical order interpretation hides the more important notion: expression evaluation. (This is probably most problematic over all.)
Even the evaluations of full expressions in statements are constraint with the lexical order, subexpressions are not (necessarily). Users should ultimately learn this besides any rules coupled to the statements. (Consider how to make a newbie get the point that ++i + ++i is meaningless in C.)
Some languages like Java and C# further constraints the order of evaluations of subexpressions to be permissive of ignorance of evaluation rules. It can be even more problematic.
This seems overspecified to users who have already learned the idea of expression evaluation. It also encourages the user community to follow the blurred mental model of the language design.
It bloats the language specification even more.
It is harmful to optimization by missing the expressiveness of nondeterminism on evaluations, before more complicated primitives are introduced.
A few languages like C++ (particularly, C++17) specify more subtle contexts of evaluation rules, as a compromise of the problems above.
It bloats the language specification a lot.
This goes totally against to simplicity to average users...
So why statements? Anyway, the history is already a mess. It seems most language designers do not take their choice carefully.
Worse, it even gives some type system enthusiasts (who are not familiar enough with the PL history) some misconceptions that type systems must have important things to do with the more essential designs of rules on the operational semantics.
Seriously, reasoning depending on types are not that bad in many cases, but particularly not constructive in this special one. Even experts can screw things up.
For example, someone emphasizes the well-typing nature as the central argument against the traditional treatment of undelimited continuations. Although the conclusion is somewhat reasonable and the insights about composed functions are OK (but still far too naive to the essense), this argument is not sound because it totally ignores the "side channel" approach in practice like _Noreturn any_of_returnable_types (in C11) to encode Falsum. And strictly speaking, an abstract machine with unpredictable state is not identical to "a crashed computer".
A statement is a special case of an expression, one with void type. The tendency of languages to treat statements differently often causes problems, and it would be better if they were properly generalized.
For example, in C# we have the very useful Func<T1, T2, T3, TResult> overloaded set of generic delegates. But we also have to have a corresponding Action<T1, T2, T3> set as well, and general purpose higher-order programming constantly has to be duplicated to deal with this unfortunate bifurcation.
Trivial example - a function that checks whether a reference is null before calling onto another function:
TResult IfNotNull<TValue, TResult>(TValue value, Func<TValue, TResult> func)
where TValue : class
{
return (value == null) ? default(TValue) : func(value);
}
Could the compiler deal with the possibility of TResult being void? Yes. All it has to do is require that return is followed by an expression that is of type void. The result of default(void) would be of type void, and the func being passed in would need to be of the form Func<TValue, void> (which would be equivalent to Action<TValue>).
A number of other answers imply that you can't chain statements like you can with expressions, but I'm not sure where this idea comes from. We can think of the ; that appears after statements as a binary infix operator, taking two expressions of type void and combining them into a single expression of type void.
Statements -> Instructions to follow sequentially
Expressions -> Evaluation that returns a value
Statements are basically like steps, or instructions in an algorithm, the result of the execution of a statement is the actualization of the instruction pointer (so-called in assembler)
Expressions do not imply and execution order at first sight, their purpose is to evaluate and return a value. In the imperative programming languages the evaluation of an expression has an order, but it is just because of the imperative model, but it is not their essence.
Examples of Statements:
for
goto
return
if
(all of them imply the advance of the line (statement) of execution to another line)
Example of expressions:
2+2
(it doesn't imply the idea of execution, but of the evaluation)
Statement,
A statement is a procedural building-block from which all C# programs are constructed. A statement can declare a local variable or constant, call a method, create an object, or assign a value to a variable, property, or field.
A series of statements surrounded by curly braces form a block of code. A method body is one example of a code block.
bool IsPositive(int number)
{
if (number > 0)
{
return true;
}
else
{
return false;
}
}
Statements in C# often contain expressions. An expression in C# is a fragment of code containing a literal value, a simple name, or an operator and its operands.
Expression,
An expression is a fragment of code that can be evaluated to a single value, object, method, or namespace. The two simplest types of expressions are literals and simple names. A literal is a constant value that has no name.
int i = 5;
string s = "Hello World";
Both i and s are simple names identifying local variables. When those variables are used in an expression, the value of the variable is retrieved and used for the expression.
I prefer the meaning of statement in the formal logic sense of the word. It is one that changes the state of one or more of the variables in the computation, enabling a true or false statement to be made about their value(s).
I guess there will always be confusion in the computing world and science in general when new terminology or words are introduced, existing words are 'repurposed' or users are ignorant of the existing, established or 'proper' terminology for what they are describing
Here is the summery of one of the simplest answer I found.
originally Answered by Anders Kaseorg
A statement is a complete line of code that performs some action, while an expression is any section of the code that evaluates to a value.
Expressions can be combined “horizontally” into larger expressions using operators, while statements can only be combined “vertically” by writing one after another, or with block constructs.
Every expression can be used as a statement (whose effect is to evaluate the expression and ignore the resulting value), but most statements cannot be used as expressions.
http://www.quora.com/Python-programming-language-1/Whats-the-difference-between-a-statement-and-an-expression-in-Python
Statements are grammatically complete sentences. Expressions are not. For example
x = 5
reads as "x gets 5." This is a complete sentence. The code
(x + 5)/9.0
reads, "x plus 5 all divided by 9.0." This is not a complete sentence. The statement
while k < 10:
print k
k += 1
is a complete sentence. Notice that the loop header is not; "while k < 10," is a subordinating clause.
In a statement-oriented programming language, a code block is defined as a list of statements. In other words, a statement is a piece of syntax that you can put inside a code block without causing a syntax error.
Wikipedia defines the word statement similarly
In computer programming, a statement is a syntactic unit of an imperative programming language that expresses some action to be carried out. A program written in such a language is formed by a sequence of one or more statements
Notice the latter statement. (although "a program" in this case is technically wrong because both C and Java reject a program that consists of nothing of statements.)
Wikipedia defines the word expression as
An expression in a programming language is a syntactic entity that may be evaluated to determine its value
This is, however, false, because in Kotlin, throw new Exception("") is an expression but when evaluated, it simply throws an exception, never returning any value.
In a statically typed programming language, every expression has a type. This definition, however, doesn't work in a dynamically typed programming language.
Personally, I define an expression as a piece of syntax that can be composed with an operator or function calls to yield a bigger expression. This is actually similar to the explanation of expression by Wikipedia:
It is a combination of one or more constants, variables, functions, and operators that the programming language interprets (according to its particular rules of precedence and of association) and computes to produce ("to return", in a stateful environment) another value
But, the problem is in C programming language, given a function executeSomething like this:
void executeSomething(void){
return;
}
Is executeSomething() an expression or is it a statement? According to my definition, it is a statement because as defined in Microsoft's C reference grammar,
You cannot use the (nonexistent) value of an expression that has type void in any way, nor can you convert a void expression (by implicit or explicit conversion) to any type except void
But the same page clearly indicates that such syntax is an expression.
A statement is a block of code that doesn't return anything and which is just a standalone unit of execution. For example-
if(a>=0)
printf("Hello Humen,I'm a statement");
An expression, on the other hand, returns or evaluates a new value. For example -
if(a>=0)
return a+10;//This is an expression because it evalutes an new value;
or
a=10+y;//This is also an expression because it returns a new value.
Expression
A piece of syntax which can be evaluated to some value. In other words, an expression is an accumulation of expression elements like literals, names, attribute access, operators or function calls which all return a value. In contrast to many other languages, not all language constructs are expressions. There are also statements which cannot be used as expressions, such as while. Assignments are also statements, not expressions.
Statement
A statement is part of a suite (a “block” of code). A statement is either an expression or one of several constructs with a keyword, such as if, while or for.
To improve on and validate my prior answer, definitions of programming language terms should be explained from computer science type theory when applicable.
An expression has a type other than the Bottom type, i.e. it has a value. A statement has the Unit or Bottom type.
From this it follows that a statement can only have any effect in a program when it creates a side-effect, because it either can not return a value or it only returns the value of the Unit type which is either nonassignable (in some languages such a C's void) or (such as in Scala) can be stored for a delayed evaluation of the statement.
Obviously a #pragma or a /*comment*/ have no type and thus are differentiated from statements. Thus the only type of statement that would have no side-effects would be a non-operation. Non-operation is only useful as a placeholder for future side-effects. Any other action due to a statement would be a side-effect. Again a compiler hint, e.g. #pragma, is not a statement because it has no type.
Most precisely, a statement must have a "side-effect" (i.e. be imperative) and an expression must have a value type (i.e. not the bottom type).
The type of a statement is the unit type, but due to Halting theorem unit is fiction so lets say the bottom type.
Void is not precisely the bottom type (it isn't the subtype of all possible types). It exists in languages that don't have a completely sound type system. That may sound like a snobbish statement, but completeness such as variance annotations are critical to writing extensible software.
Let's see what Wikipedia has to say on this matter.
https://en.wikipedia.org/wiki/Statement_(computer_science)
In computer programming a statement is the smallest standalone element of an imperative programming language that expresses some action to be carried out.
Many languages (e.g. C) make a distinction between statements and definitions, with a statement only containing executable code and a definition declaring an identifier, while an expression evaluates to a value only.