let and flet in emacs lisp - binding

I don't know if you would call it the canonical formulation, but to bind a local function I am advised by the GNU manual to use 'flet':
(defun adder-with-flet (x)
(flet ( (f (x) (+ x 3)) )
(f x))
)
However, by accident I tried (after having played in Scheme for a bit) the following expression, where I bind a lambda expression to a variable using 'let', and it also works if I pass the function to mapcar*:
(defun adder-with-let (x)
(let ( (f (lambda (x) (+ x 3))) )
(car (mapcar* f (list x)) ))
)
And both functions work:
(adder-with-flet 3) ==> 6
(adder-with-let 3) ==> 6
Why does the second one work? I cannot find any documentation where 'let' can be used to bind functions to symbols.

Unlike Scheme, Emacs Lisp is a 2-lisp, which means that each symbol has two separate bindings: the value binding and the function binding. In a function call (a b c d), the first symbol (a) is looked up using a function binding, the rest (b c d) are looked up using the value binding. Special form let creates a new (local) value binding, flet creates a new function binding.
Note that whether value or function binding is used for lookup depends on the position in the (a b c d) function call, not on the type of the looked-up value. In particular, a value binding can resolve to function.
In your first example, you function-bind f (via flet), and then do a function lookup:
(f ...)
In your second example, you value-bind f to a function (via let), and then use a value lookup:
(... f ...)
Both work because you use the same kind of binding and lookup in each case.
http://en.wikipedia.org/wiki/Common_Lisp#Comparison_with_other_Lisps

I did a quick search of the Emacs lisp manual and couldn't find any reference to 'flet, which isn't terribly surprising since that is a part of cl - the common-lisp package.
let will do a local binding as well, but it won't bind to the "function cell" for that symbol.
i.e. This works:
(let ((myf (lambda (x) (list x x))))
(eval (list myf 3)))
but
(let ((myf (lambda (x) (list x x))))
(myf 3))
fails with the error: "Lisp error: (void-function myf)"
flet on the other hand, does do the binding to the function cell, so this works:
(flet ((myf (x) (list x x)))
(myf 3))
Notice the difference being that flet allows you to use the symbol myf directly, whereas the let does not - you have to use some indirection to get the function out of the "value cell" and apply that appropriately.
In your example, the 'mapcar' did the equivalent to my use of 'eval.

#d11wq there is `funcall' for this purpose. The following works:
(defun adder-with-let (x)
(let ((f #'(lambda (x) (+ x 3))))
(funcall f 3)))
(adder-with-let 3) ;=> 6

You don't have to use flet if you do not want to. You place a function in the function cell of a local symbol defined using let as in the following example:
(let ((ALocalSymbol))
(fset 'ALocalSymbol (lambda (x) (* 2 x)))
(ALocalSymbol 4)
)
Evaluating this will return 8. Do notice the quote in front of ALocalSymbol in (let ((ALocalSymbol))...). While setq quotes symbols, fset does not.
flet is a syntactic sugar of sorts. Using a plain-old let to define nil-valued symbols, allows you to choose which "cell" of a symbol to set. You could use setq to set the symbol's value cell or fset to set the function cell.
Hope this helps,
Pablo

Related

Racket: Creating a stream using a macro instead of a function

I'm currently attempting to create a stream using a macro, as shown below:
(define-syntax create-stream
(syntax-rules (using starting at with increment )
[(create-stream name using f starting at i0 with increment delta)
(letrec
([name (lambda (f current delta)
(cons current (lambda () (name (f (+ current delta) delta)))))])
(lambda () (name f i0 delta)))
]))
What happens though is I get a compilation error later on when I try to pass it the following lambda function, which says "lambda: not an identifier, identifier with default, or keyword".
(create-stream squares using (lambda (x) (* x x)) starting at 5 with increment 2)
What I suspect is happening is that by attempting to use lambda in a macro, it's shadowing the actual lambda function in Racket. If this is true, I'm wondering in what way one can create a stream without using lambda, since as far as I can tell, there needs to be a function somewhere to create said stream.
Also this is a homework problem, so I do have to use a macro. My equivalent function for creating the stream would be:
(define create-stream
(letrec ([name (lambda (f current delta) (cons current (lambda () (name (f (+ current delta) delta)))))])
(lambda () (name f i0 delta))))
What I suspect is happening is that by attempting to use lambda in a macro, it's shadowing the actual lambda function in Racket
No, that's not correct.
The problem here is that you use f and delta in binding positions, in (lambda (f current delta) ...). That means after (create-stream squares using (lambda (x) (* x x)) starting at 5 with increment 2) is expanded, you will get code like:
(lambda ((lambda (x) (* x x)) current 2) ...)
which is obviously a syntax error.
You can see this yourself by using the macro stepper in DrRacket.
The fix is to rename the identifiers to something else. E.g.,
(define-syntax create-stream
(syntax-rules (using starting at with increment )
[(create-stream name using f starting at i0 with increment delta)
(letrec
([name (lambda (f* current delta*)
(cons current (lambda () (name (f* (+ current delta*) delta*)))))])
(lambda () (name f i0 delta)))
]))
This will make your code start running, but there are still other several bugs in your code. Since this is your homework, I'll leave them to you.
Your current problem essentially boils down to this (broken) code
(let ((x 0))
(define y x))
This is not equivalent to (define y 0) - y's definition is local to the let-binding.
The solution is to flip the definitions around and make the letrec local to the define:
(define name
(letrec (... fn definition ...)
(lambda () (fn i0))))

How to read and run procedure from argument in Scheme?

is it possible to give procedure definition as an argument and then somehow run it in the program? For example if I call (program 'write-hello '((procedure write-hello ('Hello.)))) . How can I read the procedure from argument? I spent few hours on it and can't really find any solution to it as I'm new to Scheme.
Thanks
Functions are first class citizens in Scheme: they are values that can be passed just like the more traditional data types, and the parameter name can be used as if there were a function with that name defined in the traditional way.
If you have defined a function in the normal way (using define), then you can just pass the name. But you can also make a function object using lambda, which can be used like any other value (bound to names, passed as an argument) in addition to its function-like abilities (i.e. applied to arguments).
The following are equivalent:
(define (plus a b) (+ a b))
(define plus_a (lambda (a b) (+ a b)))
And if you have the following (notice how op is being used):
(define (do_op op a b) (op a b))
Then these would also be equivalent to each other:
(do_op + 5 6)
(do_op plus 5 6)
(do_op plus_a 5 6)
(do_op (lambda (a b) (+ a b)) 5 6)
For Scheme you just pass the lambda definition like (lambda (n) (* n n)) eg.
(define (display-result procedure value)
(display (procedure value))
(display-result (lambda (n) (* n n)) 5) ; displays 25
If a procedure is bound to a name, like + or defined with define you just use that name in place of the lambda expression.
If you are after making an interpreter of some language then you need to implement this feature yourself by managing your own environment. It's not simple and if you're a newbie it will take more than hours to complete. I recomment watching the SICP videos.

Shallow and Deep Binding

I was trying to understand the concept of dynamic/static scope with deep and shallow binding. Below is the code-
(define x 0)
(define y 0)
(define (f z) (display ( + z y))
(define (g f) (let ((y 10)) (f x)))
(define (h) (let ((x 100)) (g f)))
(h)
I understand at dynamic scoping value of the caller function is used by the called function. So using dynamic binding I should get the answer- 110. Using static scoping I would get the answer 0. But I got these results without considering shallow or deep binding. What is shallow and deep binding and how will it change the result?
There's an example in these lecture notes 6. Names, Scopes, and Bindings: that explains the concepts, though I don't like their pseudo-code:
thres:integer
function older(p:person):boolean
return p.age>thres
procedure show(p:person, c:function)
thres:integer
thres:=20
if c(p)
write(p)
procedure main(p)
thres:=35
show(p, older)
As best I can tell, this would be the following in Scheme (with some, I hope, more descriptive names:
(define cutoff 0) ; a
(define (above-cutoff? person)
(> (age person) cutoff))
(define (display-if person predicate)
(let ((cutoff 20)) ; b
(if (predicate person)
(display person))))
(define (main person)
(let ((cutoff 35)) ; c
(display-if person above-cutoff?)))
With lexical scoping the cutoff in above-cutoff? always refers to binding a.
With dynamic scoping as it's implemented in Common Lisp (and most actual languages with dynamic scoping, I think), the value of cutoff in above-cutoff?, when used as the predicate in display-if, will refer to binding b, since that's the most recent on on the stack in that case. This is shallow binding.
So the remaining option is deep binding, and it has the effect of having the value of cutoff within above-cutoff? refer to binding c.
Now let's take a look at your example:
(define x 0)
(define y 0)
(define (f z) (display (+ z y))
(define (g f) (let ((y 10)) (f x)))
(define (h) (let ((x 100)) (g f)))
(h)
I'm going to add some newlines so that commenting is easier, and use a comment to mark each binding of each of the variables that gets bound more than once.
(define x 0) ; x0
(define y 0) ; y0
(define (f z) ; f0
(display (+ z y)))
(define (g f) ; f1
(let ((y 10)) ; y1
(f x)))
(define (h)
(let ((x 100)) ; x1
(g f)))
Note the f0 and f1 there. These are important, because in the deep binding, the current environment of a function passed as an argument is bound to that environment. That's important, because f is passed as a parameter to g within f. So, let's cover all the cases:
With lexical scoping, the result is 0. I think this is the simplest case.
With dynamic scoping and shallow binding the answer is 110. (The value of z is 100, and the value of y is 10.) That's the answer that you already know how to get.
Finally, dynamic scoping and deep binding, you get 100. Within h, you pass f as a parameter, and the current scope is captured to give us a function (lambda (z) (display (+ z 0))), which we'll call ff for sake of convenience. Once, you're in g, the call to the local variable f is actually a call to ff, which is called with the current value of x (from x1, 100), so you're printing (+ 100 0), which is 100.
Comments
As I said, I think the deep binding is sort of unusual, and I don't know whether many languages actually implement that. You could think of it as taking the function, checking whether it has any free variables, and then filling them in with values from the current dynamic environment. I don't think this actually gets used much in practice, and that's probably why you've received some comments asking about these terms. I do see that it could be useful in some circumstances, though. For instance, in Common Lisp, which has both lexical and dynamic (called 'special') variables, many of the system configuration parameters are dynamic. This means that you can do things like this to print in base 16 (since *print-radix* is a dynamic variable):
(let ((*print-radix* 16))
(print value))
But if you wanted to return a function that would print things in base 16, you can't do:
(let ((*print-radix* 16))
(lambda (value)
(print value)))
because someone could take that function, let's call it print16, and do:
(let ((*print-radix* 10))
(print16 value))
and the value would be printed in base 10. Deep binding would avoid that issue. That said, you can also avoid it with shallow binding; you just return
(lambda (value)
(let ((*print-radix* 16))
(print value)))
instead.
All that said, I think that this discussion gets kind of strange when it's talking about "passing functions as arguments". It's strange because in most languages, an expression is evaluated to produce a value. A variable is one type of expression, and the result of evaluating a variable is the expression of that variable. I emphasize "the" there, because that's how it is: a variable has a single value at any given time. This presentation of deep and shallow binding makes it gives a variable a different value depending on where it is evaluated. That seems pretty strange. What I think would make much more sense is if the discussions were about what you get back when you evaluate a lambda expression. Then you could ask "what will the values of the free variables in the lambda expression be"? The answer, in shallow binding, will be "whatever the dynamic values of those variables are when the function is called later. The answer, in deep binding, is "whatever the dynamic values of those variables are when the lambda expression is evaluated."
Then we wouldn't have to consider "functions being passed as arguments." The whole "functions being passed as arguments" is bizarre, because what happens when you pass a function as a parameter (capturing its dynamic environment) and whatever you're passing it to then passes it somewhere else? Is the dynamic environment supposed to get re-bound?
Related Questions and Answers
Dynamic Scoping - Deep Binding vs Shallow Binding
Shallow & Deep Binding - What would this program print?
Dynamic/Static scope with Deep/Shallow binding (exercises) (The answer to this question mentions that "Dynamic scope with deep binding is much trickier, since few widely-deployed languages support it.")

Compose example in Paul Graham's ANSI Common Lisp

Can anybody explain an example in Paul Graham's ANSI Common Lisp page 110?
The example try to explain the use &rest and lambda to create functional programming facilities. One of them is a function to compose functional arguments. I cannot find anything explaining how it worked. The code is as follows:
(defun compose (&rest fns)
(destructuring-bind (fn1 . rest) (reverse fns)
#'(lambda (&rest args)
(reduce #'(lambda (v f) (funcall f v))
rest
:initial-value (apply fn1 args)))))
The usage is:
(mapcar (compose #'list #'round #'sqrt)
'(4 9 16 25))
The output is:
((2) (3) (4) (5))
Line 2 and 6 look especially like magic to me.
The compose function returns a closure that calls each of the functions from last to first, passing on the result of each function call to the next.
The closure resulting from calling (compose #'list #'round #'sqrt) first calculates the square root of its argument, rounds the result to the nearest integer, then creates a list of the result. Calling the closure with say 3 as argument is equivalent to evaluating (list (round (sqrt 3))).
The destructuring-bind evaluates the (reverse fns) expression to get the arguments of compose in reverse order, and binds its first item of the resulting list to the fn1 local variable and the rest of the resulting list to the rest local variable. Hence fn1 holds the last item of fns, #'sqrt.
The reduce calls each the fns functions with the accumulated result. The :initial-value (apply fn1 args) provides the initial value to the reduce function and supports calling the closure with multiple arguments. Without the requirement of multiple arguments, compose can be simplified to:
(defun compose (&rest fns)
#'(lambda (arg)
(reduce #'(lambda (v f) (funcall f v))
(reverse fns)
:initial-value arg)))
destructuring-bind combines destructors with binding. A destructor is a function that lets you access a part of a data structure. car and cdr are simple destructors to extract the head and tail of a list. getf is a general destructor framework. Binding is most commonly performed by let. In this example, fns is (#'list #'round #'sqrt) (the arguments to compose), so (reverse fns) is (#'sqrt #'round #'list). Then
(destructuring-bind (fn1 . rest) '(#'sqrt #'round #'list)
...)
is equivalent to
(let ((tmp '(#'sqrt #'round #'list)))
(let ((fn1 (car tmp))
(rest (cdr tmp)))
...))
except that it doesn't bind tmp, of course. The idea of destructuring-bind is that it's a pattern matching construct: its first argument is a pattern that the data must match, and symbols in the pattern are bound to the corresponding pieces of the data.
So now fn1 is #'sqrt and rest is (#'round #'list). The compose function returns a function: (lambda (&rest args) ...). Now consider what happens when you apply that function to some argument such as 4. The lambda can be applied, yielding
(reduce #'(lambda (v f) (funcall f v))
'(#'round #'list)
:initial-value (apply #'sqrt 4)))
The apply function applies fn1 to the argument; since this argument is not a list, this is just (#'sqrt 4) which is 2. In other words, we have
(reduce #'(lambda (v f) (funcall f v))
'(#'round #'list)
:initial-value 2)
Now the reduce function does its job, which is to apply #'(lambda (v f) (funcall f v)) successively to the #'round and to #'list, starting with 2. This is equivalent to
(funcall #'list (funcall #'round 2))
→ (#'list (#'round 2))
→ '(2)
Okay, here goes:
It takes the functions given, reverses it (in your example, it becomes (#'sqrt #'round #'list)), then sticks the first item into fn1, and the rest into rest. We have: fn1 = #'sqrt, and rest = (#'round #'list).
Then it performs a fold, using (apply sqrt args) (where args are the values given to the resulting lambda) as the initial value, and with each iteration grabbing the next function from rest to call.
For the first iteration you end up with (round (apply sqrt args)), and the second iteration you end up with (list (round (apply sqrt args))).
Interestingly, only the initial function (sqrt in your case) is allowed to take multiple arguments. The rest of the functions are called with single arguments only, even if any particular function in the chain does a multiple-value return.
This example stumped me for a day. I could finally understand it by renaming some of the arguments and commenting each line before it made sense. Below is what helped me explain it to myself.
In the book example using the call:
(mapcar (compose #'list #'round #'sqrt) '(4 9 16 25))
The parameter functions becomes (#'LIST #'ROUND #'SQRT)
(defun compose (&rest functions)
(destructuring-bind (fx . fxs) (reverse functions)
;; fx becomes #'SQRT
;; fxs becomes '(#'ROUND #'LIST)
#'(lambda (&rest args) ; This is the function returned as result.
;; The args parameter will be (4) on the mapcar's first
;; iteration on the (4 9 16 25) list passed in the call:
;; (mapcar #'(compose #'List #'round #'sqrt) '(4 9 16 25)) => ((2) (3) (4) (5))
;; or e.g. the (4) in (funcall (compose #'list #'sqrt '(4)) => (2.0)
;; Note that args is not ((#'ROUND #'LIST)).
(reduce #'(lambda (x y) (funcall y x))
;; fxs is (#'ROUND #'LIST) - captuted as closure since it is now
;; locally unbound.
fxs
;; Initial value is: (apply #'SQRT '(4) => 2.0.
;; In Paul Graham's example, the mapcar passes
;; each square number individually.
;; The reverse order of parameters in the second lambda
;; first invokes: (ROUND 2.0) => 2
;; and then invokes: (LIST 2) => (2)
:initial-value (apply fx args)))))

Scheme: mapping let and set! onto lists

I am trying to map let and set! onto lists something like this:
(map (lambda (x) (let ((x #f)))) <list>)
and
(map set! <list1> <list2>)
But, of course, neither is working.
Is there a way to do this? Any advice is appreciated.
Thanks.
The real problem is that I am trying to find a way to pattern match letrec. I need to be able to pattern match:
(letrec ((var val) ...) expr0 expr1 ...)
and convert it -- using match-lambda -- to an equivalent call using only let and set! This is the template I am trying to emulate:
(letrec ((var val) ...) expr0 expr1 ...)
==>
(let ((var #f) ...)
(let ((temp val) ...)
(set! var temp) ...
(let () expr0 expr1 ...)))
The problem is translating this into syntax that match-lambda accepts. Here is what I was working on, assuming there was a way to accomplish the original question:
(match-rewriter (`(letrec((,<var> ,<val>) ...) ,<expr> ...)
`((map (λ (x) (let ((x #f)))) ,<var>)
(let ((temp ,<val>)))
(map set! ,<var> temp)
(let () ,#<expr>))))
Any advice is appreciated.
Thanks.
You cannot do that. Short of using eval, variable names are generally not allowed to be dynamic (basically anything that isn't a symbol literal). This is by design.
If your variable names really are literals, and you just want a way to bind multiple variables at once, you can use let-values (SRFI 11) or extended let (SRFI 71).
Edit to match OP's edit: What you want to do sounds like the letrec definition given here. However, that macro uses syntax-case, not match-lambda or the like. You may be able to use it as a starting point, though.
This is the code you want:
(define (rewrite-letrec l)
(match l
[(list 'letrec (list (list vars rhss) ...)
exprs ...)
(let ([tmps (map (λ _ (gensym)) vars)])
`(let (,(map (λ (v) `(,v #f)) vars))
(let (,(map (λ (tmp rhs) `(,tmp ,rhs)) tmps rhss))
,#(map (λ (v t) `(set! ,v ,t)))
(let () ,#exprs))))]))
There are several differences here. One is that the lets are nested. Second, we're constructing code, not trying to run it.

Resources