LET and SETF in commonLISP - let

From what my teacher told me, I should use let to declare local variables and setf to declare global variables.
I'm tried running the following code:
(let (state-list (problem-initial-state problem))
(print state-list))
and I get NIL.
However, when I try the following:
(setf state-list (problem-initial-state problem))
(print final-list)
I get the desired value (the value in problem-initial-state problem).
Why is that?
PS: I apologize for these begginer questions, I'm getting a hard time getting into LISP, coming from a C background.

You are missing a couple of parens in your let forms:
(let ((a 1)
(b 2))
(print (list a b)))
will print (1 2).
Your form
(let (state-list (problem-initial-state problem))
(print state-list))
binds state-list to nil and problem-initial-state to problem.

Related

Function outputs a list but returns nil

I call a function, which outputs a list, I want to use afterwards. I try to bind the function's output to a variable, but instead of the list it gets assigned NIL.
My call and output (observe the newline in the output):
(nqthm-eval `(myghs 1 NIL ,g1)) ==> '(T (B . E) (D . D))
When I try to bind this output to a variable v it gets assigned NIL:
(setq v (nqthm-eval `(myghs 1 NIL ,g1))) ==> '(T (B . E) (D . D))
NIL
And an equality check afterwards indeed gives:
(equal v NIL) ==> T
It seems to me, that the function call to nqthm-eval is outputting the list and returning NIL, although I don't understand LISP enough for this yet.
My question: Is there a way to get the list part of the output/return of my function like (car (nqthm-eval ...)) or (get_output (nqthm-eval ...)) from the 'outside'?
There is a difference between a function's return value and its output.
The return value is just the value (or values) of the last form and is captured by setq et al.
The output is sent to a stream and can only be captured from it.
E.g.,
(defun foo1 (x)
(princ (1+ x))
(1- x))
(foo1 12)
will print 13 and return 11.
If you want to capture both, you need
(defun foo2 (x)
(values (1+ x) (1- x)))
(setf (values a b) (foo2 17))
and now a is 18 and b is 16.
PS. Actually, if you do not have control over the function source code and still want to capture its output, you can do it if you know where it sends its output. E.g.:
(setq b (with-output-to-string (*standard-output*)
(setq a (foo1 1))))
now b is "2" (a string!) while a is 0 (a number!)

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.")

Scheme console printing

Just started with Scheme. I'm having problem with printing on console.
A simple list printing example:
(define factorial
(lambda (n)
(cond
((= 0 n) 1)
(#t (* n (factorial (- n 1)))))))
I want to print n, every time the function is called. I figured that I can't do that within the same function? Do I need to call another function just so I can print?
Printing in Scheme works by calling display (and possibly, newline).
Since you want to call it sequentially before/after something else (which, in a functional (or in the case of Scheme, functional-ish) language only makes sense for the called functions side-effects), you would normally need to use begin, which evaluates its arguments in turn and then returns the value of the last subexpression. However, lambda implicitly contains such a begin-expression.
So in your case, it would go like this:
(lambda (n)
(display n) (newline)
(cond [...]))
Two remarks:
You can use (define (factorial n) [...]) as a shorthand for (define factorial (lambda (n) [...])).
The way you implement factorial forbids tail call-optimization, therefore the program will use quite a bit of stack space for larger values of n. Rewriting it into a optimizable form using an accumulator is possible, though.
If you only want to print n once, when the user calls the function, you will indeed need to write a wrapper, like this:
(define (factorial n)
(display n) (newline)
(inner-factorial n))
And then rename your function to inner-factorial.

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.

let and flet in emacs lisp

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

Resources