Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between Expression vs Function

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:

  1. A function has a name and can be referred to (though an expression could be assigned to a variable?)
  2. A function can take parameters (is an expression able to?)
  3. A function can have a scope/encapsulation and contain multiple statements.
like image 301
David542 Avatar asked Dec 30 '25 15:12

David542


1 Answers

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.

like image 150
Silvio Mayolo Avatar answered Jan 03 '26 13:01

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!