4 ms·
Not really. Python's lambda does pretty much what you would expect from Scheme. It creates a callable the binds arguments to parameters in a lexically scoped
by raymondh 6y ago
Not really.
Python's lambda does pretty much what you would expect from Scheme. It creates a callable the binds arguments to parameters in a lexically scoped namespace and then evaluates the body of the lambda in that namespace. And with an open parenthesis, you can write multiline lambdas and indent it however you want.
All the usual wizardry is possible:
>>> (
lambda n: (lambda fact: fact(n, fact))(
lambda n, inner: 1 if n == 0 else (n * inner(n - 1, inner))
)
)(5)
120
Also, Python has rough equivalents to some special forms in Scheme:
(if testexp posexp negexp) ⟶ (posexp if testexp else negexp)
(cond (p1 e1) (p2 e2) (else e3) ⟶ (e1 if p1 else e2 if p2 else e2)
(begin e1 e2 e2) ⟶ [e1, e2, e3][-1]
(and e1 e2 e3) ⟶ (e1 and e2 and e3)
(or e1 e2 e2) ⟶ (e1 or e2 or e3)
Some statements do have a functional form but aren't well known:
class keyword ⟶ type(name, bases, namespace)
import keyword ⟶ __import__(name, globals, locals, fromlist)
You have map(), filter(), partial(), and reduce(). The operator module provides function equivalents for most operators. Also, the itertools were directly based on their equivalents in functional languages or array manipulation languages.
That said, Python does lack some essential tooling that you would really miss:
- There is no way to create new special forms.
- Some important special forms are missing: let, let*, and letrec
- The language spec precludes tail call optimization.
- Some Python statements lack functional equivalents: try/except, with-statement, and assert-statement
- raymondh 6y agoActually there is a let and let* equivalent as well: (let* ((v1 e1) (v2 e2)) e3) ⟶ ((v1:=e1), (v2:=e2), e3)[-1] Dr. Racket example: > (let* ((x (+ 3 4)) (y (* x x))) (+ y (- x) 8)) 50 Python equivalent: >>> ((x:=3+4), (y:=x**2), y-x+8)[-1] 50
- Iwan-Zotow 6y agoYes, with walrus expression, lambda gains a lot of flexibility
- c-cube 6y agoExcept : - python scoping is not really lexical (and it captures variables, not the values they contain) - python is statement based, so lambdas are less powerful than in scheme. So not really the same thing.