isBound? predicate in scheme - scheme

Does anyone have a suggestion on how i can check if variable x is bound or not?
I want to differ between unbound variables and symbols for example but the symbol? predicate is not good here because (symbol? x) give me an error.
i deal only with unbound variables!
i'll give you an example:
(pattern-rule
`(car ,(?'expr))
(lambda (expr) `,(car (fold expr))))
this code is part of a folder procedure which is part of a parser.
the returned evaluation on (fold '(car (cons '1 '2))) is '1
the returned evaluation on (fold '(car x)) should be (car x) (i mean, the string (car x))
but i can't figure out how to do this part!

I understand that you are writing your own parser? If so, you need to have an explicit representation of the environment. Each time you encounter a binding construct such as lambda or let, you add the bound variables to the environment. When you need to found out if a variable is bound or not, you look it up in the environment - if it is present, then it is bound, if not it is undbound.

Related

What is the use of 'when' in Scheme?

I'm triying to use when in Scheme but i dont know why at the last element of my list appears .#void>.
Here is my code
(define (genlist x y)
(when
(< x y)
(cons x (genlist (+ x 1) y))))
And this is my output =>
(2 3 4 5 6 7 8 9 . #void>)
We use when when we need to write an if without an else part, and/or when we need to write more than one expression inside the if. Only the last expression's value gets returned, hence we use it mostly for the side effects. To understand it better, in Racket this:
(when <condition>
<exp1>
<exp2>
<exp3>)
Is equivalent to this:
(if <condition>
(begin
<exp1>
<exp2>
<exp3>)
(void)) ; implementation-dependent
The same considerations apply to unless, except that the condition is surrounded with a (not ...).
The source of your problems (and the reason why it's a code smell to have an if without an else) is that your code is not handling the case when (>= x y). Ask yourself, what should you do in that case? Simple, return an empty list! that's the base case of the recursion that's missing from your code.
You would need to use (if (< x y) (cons ...) '()) to produce a proper list.
when (and it's counterpart unless) is mostly for doing side effects (like printing something out) in a context where the result is not used.
e.g. (when debug-mode? (print "got here"))
when is an one armed ifs with implicit begin. The following examples are the same:
(if (any odd? lst)
(begin
(set! some-binding #t)
(display "Found an odd element")))
(when (any odd? lst)
(set! some-binding #t)
(display "Found an odd element"))
And you can use unless instead of using not in the predicate:
(if (not (any odd? lst))
(set! some-binding #f))
(unless (any odd? lst)
(set! some-binding #f))
Peter Norvig made a nice book about Lisp style and in it he addresses this:
Be as specific as your data abstractions warrant, but no more.
if for two-branch expression
when, unless for one-branch statement
and, or for boolean value only
cond for multi-branch statement or expression
So while you can write all your logic using if it will not be the easiest code to read. Other might use the term principle of least surprise. Even though the book is for Common Lisp much of it can be used in Scheme as well. It's a good read if you want to program any lisp dialect professionaly.
For when and unless this is applies much better to Scheme as you have no idea what an implementation might return in the event the predicate evaluates to #f while in CL you could abuse when since it's destined to return nil in such cases.
In you code you are trying to return something and letting the implementation choose what should happen when the predicate failes is what causes the #<void>. When the return matter you should always use two armed if:
(if test-expression
then-expression
else-expression)
Note there is no else keyword.

Error: (/) bad argument type: #<unspecified> Chicken Scheme Square root approximation

I am following the SICP lectures from MIT, and this is what I tried to find the square root approximation of a number by Heron of Alexandria's method. This is my first time trying out lisp, sorry for making noobie mistakes.
(define guess 1)
(define (avg a b)
(/ (+ a b) 2))
(define (try guess x)
(if (goodEnough guess x)
guess
(improve guess x)))
(define (improve guess x)
(define guess (avg guess (/ x guess)))
(try guess x)
)
(define (goodEnough guess x)
(= guess (avg guess (/ x guess))))
(print (try 1 25))
I am using Chicken scheme compiler to print this. This is the output:
Error: (/) bad argument type: #<unspecified>
Call history:
1.a.SquareRootApproximation.scm:29: try
1.a.SquareRootApproximation.scm:17: goodEnough
1.a.SquareRootApproximation.scm:27: avg
1.a.SquareRootApproximation.scm:19: improve <--
Updated: I have changed my approach towards this problem using lisp with more abstraction, yet I can't figure out what this new error wants to imply. Any fixes? Thanks!
The value #<unspecified> is basically "void" in other languages. It is used as a return value whenever some procedure has nothing useful to return (for example, print will return this). It is also in some situations used as a temporary placeholder value, for example when handling an inner define.
Normally this temporary placeholder should not be visible to the user of the language, but it appears you've hit a strange edge case in the language (congratulations! This happens rarely). The error happens because (define guess (avg guess (/ x guess))) in the improve procedure is simultaneously defining a variable and using that variable. The behaviour of doing this is not well-specified, and some Scheme implementations will do what CHICKEN is doing (Guile, Gauche, Gambit) whereas others will give a somewhat more meaningful error message (MIT, Scheme48, Racket). The reason this is ill-specified has to do with the fact that inner define expands to letrec, because it allows mutually recursive procedures to be defined, but that creates a bit of an issue: what should happen for (define a b) (define b a), for example?
Your intention seems to be using the old guess variable that's passed as input to the procedure, so instead of using define you could use let to bind a new value for guess (how this should behave is well-specified), or just use a different name for it, like new-guess.

Scheme: What is the difference between define and let when used with continutation

I'm wondering the difference between the two following code:
(define cont2 #f)
(call/cc (lambda (k) (set! cont2 k)))
(display "*")
(cont2 #f)
and
(let [(cont #f)]
(call/cc (lambda (k) (set! cont k)))
(display "*")
(cont #f))
In my opinion, the correct behavior of these two programs should be printing '*' infinitely.
However, the first one only prints one '*' and exits,
while the second one gives the correct behavior.
So I'm confused. Is there something special done with define
or the continuation is not what I thought - all the following programs until the end of the program, it seems to have a boundary or something.
Another guess is that the top-level of environment is special treated, like this:
(define (test)
(define cont2 #f)
(call/cc (lambda (k) (set! cont2 k)))
(display "*")
(cont2 #f))
(test)
This works, but why?
Thank you for your help!
In Racket, each top-level expression is wrapped with a prompt.
Since call/cc only "captures the current continuation up to the nearest prompt", in your first example, none of the other top-level expressions are captured, so applying cont2 to #f results in just #f.
Also, wrapping the first example in begin won't change things since a top-level begin implicitly splices its contents as if they were top-level expressions.
When you are at the top-level, the continuation of (notice the prompt character '>'):
> (call/cc (lambda (k) (set! cont2 k)))
is the top-level read-eval-print-loop. That is, in your first code snippet you enter the expressions one-by-one, going back to the top-level after each. If instead you did:
(begin
(define cont3 #f)
...
(cont3 #f))
you'd get infinite '*'s (because you got back to top-level only at the completion of the begin). Your third code snippet is an instance of this; you get infinite '*'s because the continuation isn't the top-level loop.
It's not only in your opinion. If your doing this in an R5RS or R6RS both not behaving the same is a violation of the report. In racket (the r5rs implementation) it probably is violating since I did test their plt-r5rs and it clearly doesn't loop forever.
#lang racket (the default language of the implementation racket) doesn't conform to any standard so, like perl5, how it behaves is the specification. Their documentation writes a lot about prompt tags which reduces the scope of a continuation.
There are arguments against call/cc that comes to mind when reading this question. I think the interesting part is:
It is telling that call/cc as implemented in real Scheme systems never
captures the whole continuation anyway: Many Scheme systems put
implicit control delimiter around REPL or threads. These implicit
delimiters are easily noticeable: for example, in Petite Chez or
Scheme48, the code
(let ((k0 #f))
(call/cc (lambda (k) (set! k0 k)))
(display 0)
(k0 #f))
prints the unending stream of zeros. If we put each operation on its
own line (evaluated by its own REPL):
(define k0 #f)
(call/cc (lambda (k) (set! k0 k)))
(display 0)
(k0 #f)
the output is mere 0 #f.
I'm not sure if I'm against call/cc as a primitive (I believe your tools should give you the possibility to shoot yourself in the foot). I feel I might change my mind after writing a Scheme compiler though so I'll come back to this when I have.
This also works, don't ask me why. (Call/cc just blows my mind)
(define cont2 #f)
((lambda ()
(call/cc (lambda (k) (set! cont2 k)))
(display "*")
(cont2 #f)))
In your test define the three lines are within an implicit begin struction that you call together that is invoked at the top level. In my version I've just made an anonymous thunk to which invokes itself. In your first define of cont2, your define is just creating a placeholder for the value, and your function calls after aren't linked together within and environment,

How to define a compile time available function in scheme?

How the scheme compiler determines, which functions will be available during macroexpansion?
I mean such low level mechanisms, like syntax-case, where you can not only generate patter substitution, but call some functions, at least in a fender part
Edit:
I mean, I need to use an ordinary function in macroexpansion process. E. g.:
(define (twice a)
(declare 'compile-time)
(* 2 a))
(let-syntax ((mac (lambda (x)
(syntax-case x ()
((_ n) (syntax (display (unsyntax (twice n)))))))))
(mac 4))
Where n is known to be a number, and evaluation of (twice n) occurs during expansion.
Every Scheme compiler determines the functions referenced by a macro expansion. In your case, the compilation of 'let-syntax' will result in the compiler determining that 'twice' is free (syntactically out-of-scope within 'let-syntax'). When the macro is applied, the free reference to the 'twice' function will have been resolved.
Different Scheme compilers perform the free value resolution at possibly different times. You can witness this by defining 'twice' as:
(define twice
(begin (display 'bound')
(lambda (x) (* 2 x))))
[In your case, with let-syntax it will be hard to notice. I'd suggest define-syntax and then a later use of '(mac 4'). With that, some compilers (guile) will print 'bound' when the define-syntax is compiled; others (ikarus) will print 'bound' when '(mac 4)' is expanded.]
It depends what macro system you are using. Some of these systems allow you to call regular scheme functions during expansion. For example, Explicit Renaming Macros let you do this:
(define-syntax swap!
(er-macro-transformer
(lambda (form rename compare?)
...
`(let ((tmp ,x))
(set! ,x ,y)
(set! ,y tmp)))))
That said, the macro systems available to you will depend upon what Scheme you are using.

Scheme pass-by-reference

How can I pass a variable by reference in scheme?
An example of the functionality I want:
(define foo
(lambda (&x)
(set! x 5)))
(define y 2)
(foo y)
(display y) ;outputs: 5
Also, is there a way to return by reference?
See http://community.schemewiki.org/?scheme-faq-language question "Is there a way to emulate call-by-reference?".
In general I think that fights against scheme's functional nature so probably there is a better way to structure the program to make it more scheme-like.
Like Jari said, usually you want to avoid passing by reference in Scheme as it suggests that you're abusing side effects.
If you want to, though, you can enclose anything you want to pass by reference in a cons box.
(cons 5 (void))
will produce a box containing 5. If you pass this box to a procedure that changes the 5 to a 6, your original box will also contain a 6. Of course, you have to remember to cons and car when appropriate.
Chez Scheme (and possibly other implementations) has a procedure called box (and its companions box? and unbox) specifically for this boxing/unboxing nonsense: http://www.scheme.com/csug8/objects.html#./objects:s43
You can use a macro:
scheme#(guile-user)> (define-macro (foo var)`(set! ,var 5))
scheme#(guile-user)> (define y 2)
scheme#(guile-user)> (foo y)
scheme#(guile-user)> (display y)(newline)
5
lambda!
(define (foo getx setx)
(setx (+ (getx) 5)))
(define y 2)
(display y)(newline)
(foo
(lambda () y)
(lambda (val) (set! y val)))
(display y)(newline)
Jari is right it is somewhat unscheme-like to pass by reference, at least with variables. However the behavior you want is used, and often encouraged, all the time in a more scheme like way by using closures. Pages 181 and 182(google books) in the seasoned scheme do a better job then I can of explaining it.
Here is a reference that gives a macro that allows you to use a c like syntax to 'pass by reference.' Olegs site is a gold mine for interesting reads so make sure to book mark it if you have not already.
http://okmij.org/ftp/Scheme/pointer-as-closure.txt
You can affect an outer context from within a function defined in that outer context, which gives you the affect of pass by reference variables, i.e. functions with side effects.
(define (outer-function)
(define referenced-var 0)
(define (fun-affects-outer-context) (set! referenced-var 12) (void))
;...
(fun-affects-outer-context)
(display referenced-var)
)
(outer-function) ; displays 12
This solution limits the scope of the side effects.
Otherwise there is (define x (box 5)), (unbox x), etc. as mentioned in a subcomment by Eli, which is the same as the cons solution suggested by erjiang.
You probably have use too much of C, PHP or whatever.
In scheme you don't want to do stuff like pass-by-*.
Understand first what scope mean and how the different implementation behave (in particular try to figure out what is the difference between LISP and Scheme).
By essence a purely functional programming language do not have side effect. Consequently it mean that pass-by-ref is not a functional concept.

Resources