What is the formal difference between an expression and a function? I know the difference by looking at it, but I'm looking for a thorough understanding of it. For example, showing some examples from Scheme or Python:
; scheme
(display "hello") # expression
((lambda () (display "hello"))) # unnamed lambda
(define hi (lambda () (display "hello"))) # named lambda
# python
>>> print ('hello')
>>> lambda: print ('hello')
>>> hi = lambda: print ('hello')
In my rudimentary thinking, I thought the differences are:
You might be comparing apples to oranges here. An expression is a syntactic form. It's a part of your code and describes how the code is parsed. a + b and print(x) are expressions, but so are a, b, and x. Expressions are generally made of smaller expressions, often several layers deep.
A function, on the other hand, is concerned with semantics, not syntax. It's a runtime value. One might say that
lambda x: x + 1
is a function. To be completely correct, I would say that those letters parse as an expression which, when evaluated by the Python interpreter, produces a function. But that's quite wordy, so we usually skip the middle man and just say the lambda is a function.
It makes no sense to assign an expression to a variable. If I write x = 1 + 1, I'm not assigning the expression 1 + 1 to the variable. I'm assigning the result of calculating one plus one to that variable. On the other hand, if I write x = lambda: 2, then I am actually assigning a function to the variable x. Functions exist at runtime; expressions are purely a parsing construct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With