3

I'm curious how a part of Peter Norvig's Lisp interpreter works. One can define functions in this Lisp interpreter...how does this work? I'm a beginner, and just would like a simple explanation.

There's one part that might be related where it says

elif x[0] == 'define':         # (define var exp)
        (_, var, exp) = x

http://norvig.com/lispy.html

1 Answer 1

3

In this case, x[0] is define, x[1] is the variable name, and x[2] is the expression. So, in Python, _, var, exp = x is a "destructuring assignment", which destructures the array x into its constituent elements, and assigns them to the variables on the left-hand side.

Sign up to request clarification or add additional context in comments.

9 Comments

how does defining functions work though? how does the interpreter understand (define (square x) (* x x)) ?
@tekknolagi: (define (square x) (* x x)) is syntactic sugar for (define square (lambda (x) (* x x))). It's pretty obvious here that var is square and exp is (lambda (x) (* x x)).
how does it hold the user defined function in memory and then use it when the user calls (square 5) ?
@tekknolagi: lambda creates a function object. In Scheme (just like in Python, JavaScript, etc.), functions are first-class: you can pass them around like other objects. Additionally (unlike other objects), you can call them.
@tekknolagi: The arguments passed to the Python lambda, of course. (Read up on how to use variable-arity functions in Python.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.