Continuation in Scheme with lambda with no arguments - scheme

So I am dealing with continuations and have something like this:
(or
(call/cc (lambda (cont)
...
(if ( ... )
(cons randomList (lambda() (cont #f)))
#f)})}
( do something else)
I was wondering what the difference between (lambda() (cont #f)) and (cont #f) are. I get the answer I want with the lambda and something wrong without. Could someone explain the difference? Thanks.

A nullary (zero arguments) lambda used in this way is called a thunk.
Thunks are used in Scheme to defer the execution of some piece of code. Suppose, for example, that we're talking about (display #f) instead of (cont #f). If you wrote (display #f) directly, then when the code execution reached that point, it'd display #f straight away, whereas if you wrapped it in a thunk ((lambda () (display #f))), it wouldn't display the #f until you invoked the thunk.
Back to your code, a (cont #f) in the code would cause an immediate jump at the point where the continuation is invoked. Wrapping it in a thunk delays the invocation of the continuation until you invoke the thunk.

Related

Why doesn't my program produce any output?

I am looking to write a Scheme function numofatoms that determines the number of elements in a list.
For example, (numOfSymbols '((1 3) 7 (4 (5 2) ) ) should return 6.
What I have so far:
;(1 3) 7 (4(5 2)) the list
(define (numofatoms lst) ;defining a numofatoms function
(define (flatten x) ;defining a flatten function
(cond ((null? x) '())
((pair? x) (append (flatten (car x)) (flatten (cdr x))))
(else (list x))))
(length (flatten lst)))
(numofatoms '((1 3) 7 (4(5 2)))); calling the function
After defining numofatoms and flatten I don't see any errors but the program is not working. It doesn't produce any outputs.
The posted code works fine if you load it and call numofatoms from the REPL. I presume that OP is either calling load from the REPL or running the code as a script from the command-line, and when either of these is done OP sees no output. The REPL evaluates and prints results (hence the P), but when you load code that isn't necessarily what happens.
When an expression is evaluated in the REPL, the value to which the expression evaluates is printed. There may be an expectation that the value of the final expression in a file will be printed when the file is loaded into the REPL, but that expectation will not be rewarded.
The load procedure is not standardized for R6RS; here it is implementation-specific, and the particulars depend upon the implementation. For Chez Scheme, load returns an unspecified value, so there should be no expectation of seeing anything useful when a file is successfully loaded.
Both R5RS and R7RS have load procedures described in the standards, but both leave it unspecified whether the results of evaluating the expressions in a file are printed.
The details of any script mechanism for Scheme programs is entirely dependent upon the implementation. But, when you run a script from the command-line your are not in a REPL, so again there should be no expectation that the results of evaluating various forms in the file will be printed to the terminal window.
If you want a Scheme file or script to print something, you have to make it do that. If the final line of the posted file is changed to (display (numofatoms '((1 3) 7 (4(5 2))))) (newline), the program will display the result of calling numofatoms whenever it is run.

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.

isBound? predicate in 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.

How to use check-expect in Racket

I am trying to use the check-expect function in scheme but I keep being told its an unbound identifier for check-expect. Isn't check-expect a function I can use already? Below is my code:
#lang racket
(define contains (lambda (item list*)
(if (equal? list* '())
#f
(if (equal? item (car list*))
#t
(contains item (cdr list*))))))
(define z (list 1 2 3))
(define q (list 4 5 6))
(define p (list "apple" "orange" "carrot"))
(check-expect (contains 1 z) #t)
Old question, but answer for the googlers:
You can (require test-engine/racket-tests), which defines check-expect.
Note that, unlike BSL, you'll have to run the tests with (test).
check-expect is not technically built into scheme or Racket automatically.
Note that you are using #lang racket. That is the professional Racket language, and that language expects you to know and state explicitly what libraries to import. It will not auto-import them for you.
(Now, you could require a unit testing library; there is one that comes with the Racket standard library.)
But if you are just starting to learn programming, it makes much more sense to use one of the teaching languages within Racket.
For the code you're using above, I suspect you'll probably want this instead. Start DrRacket and choose "Beginner Student Language" from the "How to Design Programs" submenu in the "Language" menu.
See http://www.ccs.neu.edu/home/matthias/HtDP2e/prologue.html for more details.
I've managed to come up with this workaround:
At the top of the file (but after #lang racket) added a line
(require rackunit)
Instead of (check-expect) I've used
(check-equal? (member? "a" (list "b" "a")) #f )
Unlike in check-expect, tests must be added after the function definitions.
If the checks are successful, there is no output. Only when a tests fails, the output looks like this:
--------------------
FAILURE
name: check-equal?
actual: #f
expected: #t
expression: (check-equal? #f (member? "a" (list "b" "a")))
message: "test"
More Info: RackUnit documentation
I took a class using DrRacket and looked at the first assignment in Terminal (Mac).
The line in this file, automatically added by DrRacket, which made check-expect available is:
#reader(lib "htdp-beginner-reader.ss" "lang")((modname basic) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
As a side note, I wanted to try a Racket program without DrRacket. Just to test, I decided to do (+ 1 2). To get it to work, my file looks like this:
#! /Applications/Racket\ v6.2.1/bin/racket
#lang racket
(+ 1 2)
I run it in Terminal like this:
racket test.rkt
I put this in .bash_profile:
alias racket='/Applications/Racket\ v6.2.1/bin/racket'

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,

Resources