You appear to be using the Homebrew plt-racket package, which is a distribution of Minimal Racket, which doesn't include all the packages by default. The quick fix would be to install the swindle package yourself. Just use the raco command-line tool: raco pkg install swindle However, you might find having...

scheme,coroutine,continuations,guile,delimited-continuations

Something like this: (define (make-generator procedure) (define last-return #f) (define last-value #f) (define last-continuation (lambda (_) (procedure yield))) (define (yield value) (call/cc (lambda (continuation) (set! last-continuation continuation) (set! last-value value) (last-return value)))) (lambda args (call/cc (lambda (return) (set! last-return return) (if (null? args) (last-continuation last-value) (apply last-continuation args)))))) Used like...

variables,binding,scheme,lisp,common-lisp

Because Common Lisp has a different namespace for functions, you need to use symbol-function or fdefinition. CL-USER> (defun foo (a) (+ 2 a)) FOO CL-USER> (defun debug-foo (a) (format t " DEBUGGING FOO: ~a" a) (+ 2 a)) DEBUG-FOO CL-USER> (defun debug-foo-again (a) (format t " DEBUGGING ANOTHER FOO: ~a"...

You were close - but make sure you understand what is a full-house in the first place, and the correct way to use the boolean connectors in this case. Try this: (define is-full-house? (lambda (listy) (let ((sorted-list (sort listy <=))) (or (and (= (first sorted-list) (second sorted-list) (third sorted-list)) (=...

Here is a solution with for/fold: (define (n-grams/fold words n) (for/fold ([n-grams '()] [remaining-words words]) ([_ (in-naturals)] ; loop forever #:break (< (length remaining-words) n)) (values (cons (take remaining-words n) n-grams) (rest remaining-words)))) And here is one using foldl: (struct state (n-grams remaining-words) #:transparent) (define (n-grams/foldl words n) (foldl (λ...

You tagged this as both Common Lisp and Racket, which are two completely different languages. If you're using Racket or Scheme and want to return from a function early, you can do it using a continuation: (define (my-function x y) (call-with-current-continuation (lambda (return) (when x (return y)) ;; Rest of...

function,functional-programming,scheme

I will call your second function y. Writing in pseudocode, x [] -> 0 x [a . b] -> x a + x b , if list a x [a . b] -> 1 + x b , else, i.e. if not (list a) y [] -> 0 y [a...

scheme,racket,base,hexavigesimal

Honestly, I'm not entirely sure what your code is doing, but either way, it's far more complicated than it needs to be. Converting a base-26 string to an integer is quite straightforward just by using some higher-order constructs: ; (char-in #\a #\z) -> (integer-in 0 25) (define (base-26-char->integer c) (-...

In general there is no way to see body of a closure at runtime. The "body" is part of the source code. It gets compiled into bytecode (and later to machine code by the JIT). The closure consists at runtime of the captured values for the free variables in the...

functional-programming,scheme,tail-recursion,callstack

Racket allows you to store values in the call stack. You can use this to keep track of the depth. Here is how I would do it: #lang racket ;;; This module holds the tools for keeping track of ;;; the current depth. (module depth racket (provide (rename-out [depth-app #%app])...

Simply define another function that takes the word argument and passes it and a constant nodes argument to extract-disjunct. Using currying, you can make this work for any constant nodes: (define ((curried-extract-disjunct nodes) word) (extract-disjunct word nodes)) (map (curried-extract-disjunct nodes) words) ...

(use-modules (srfi srfi-1)) is indeed the correct way to import SRFI 1, in top-level programs and in the REPL. However, based on your previous question, I believe you may actually be writing a module instead, in which case the syntax is a little different. You'd use #:use-module (srfi srfi-1) inside...

Here is a solution. To get the ball rolling the first element of the list is chosen as a candidate to be returned. Then for each element of the remaining elements in the list, we randomly choose if the candidate is to be replaced. For example: For a list with...

First of all, good for you for wanting to come up with a cleaner solution! You're right that there's a more elegant way to do what you've attempted. To start, using subprocess is almost certainly overkill in your particular use-case. The racket/system module provides a simpler interface that should be...

clojure,scheme,lisp,common-lisp

The empty product is 1. The reason is that 1 is a neutral element for *. If you have the product of 2 and 3 and then multiply by the product of nothing, you will get 2*3*1 = 6. We can write (product (product 2 3) (product)) = (product 6...

Your list is not a proper list but a dotted list. All higher order functions like filter, fold, map, ... require the lists to be proper so such list cannot be used. I'm wondering if perhaps the reason you are stuck with such list is because of a bug in...

The big-bang form works by passing a "state" throughout handlers, which is then handed off to the to-draw handler to paint the picture that will be flushed to the screen. For starters, you should lift your drawing code into big-bang's to-draw clause: (big-bang null (to-draw (λ (state) (text "---Small Shack---"...

The problem is that your algorithm is too eager—once it finds two elements that are equal, it immediately throws away that element and keeps checking. In actuality, finding two equal elements is not enough, since your algorithm might have to backtrack if it finds an incomplete match. The easiest way...

There are a number of things that I don't think you're entirely understanding about how all these elements of Scheme fit together. First of all, the term "tuple" is a little ambiguous. Scheme does not have any formal tuple type—it has pairs and lists. Lists are themselves built from pairs,...

First of all, why not use #lang racket instead of r5rs? Racket is very much built with education in mind. It even has various teaching languages for use with the How to Design Programs textbook (or its second edition, which is still being worked on). Racket's implementation of R5RS is...

Starting with your definition: (define (myfunc L n) (if (= n 0) empty (cons (list-ref L (random 26)) (myfunc L (- n 1))))) Functions that take Functions Because Schemes treat functions as first class values, myfunc can be passed as a function to another function. We can write a second...

scope,scheme,pattern-matching,racket

Use ==: (match '(cat . doge) [`(,a . ,b) (match b [(== a) #t] [_ #f])] [_ "Not a pair"]) Due to the placement in the docs, == is easy to overlook....

That's because append is not a mutating function. It returns a new list with its arguments appended together. By convention in Scheme, functions that perform mutation end with an exclamation mark, such as set!. You can use set! to modify new-list so that it is updated, like this: (set! new-list...

There are a couple things wrong: first notice that every time you recursively call position, index is bound to zero. Second, look at your else branch. (+ 1 index) evaluates to 1 (it does not change any variables) and index evaluates to 0. This branch can only evaluate to one...

scheme,racket,flatten,list-processing

The first implementation shown is self-contained but incorrect, and it's not calling Racket's built-in flatten - it's simply calling itself recursively, rename it to see what I mean. Here's a fixed version: (define (my-flatten lst) (cond ((null? lst) empty) ; you wrote `list` instead of `lst` ((pair? (car lst)) ;...

There are two kinds of lists: empty ones and pairs. Therefore we have the following structure: (define (all xs) (cond [(empty? xs) ...] [(pair? xs) ...] [else (error 'all "expected a list, got: " xs)])) Since all elements in the empty list are true, we get: (define (all xs) (cond...

Polynomial operations can be complicated, so it is important to break the task up into many small operations. In particular you need to have a separate function that prints a polynomial. Below you will see how simplify can replace the two terms with the same exponent. What's missing is a...

The random function works fine, but your code is wrong. You want this instead: (define random-abcd (let ([n (random 4)]) (cond [(equal? n 0) 'A] [(equal? n 1) 'B] [(equal? n 2) 'C] [else 'D]))) In your original example, you generated a new random number for every comparison. This seems...

macros,polymorphism,scheme,overloading

I think that Chris is right in that this is not really a job for macros. A simple procedure might be what you're looking for: (define (lookup key container) (cond ((type1? container) (type1-lookup key container)) . ; repeat for whichever types.. . ((typeN? container) (typeN-lookup key container)) (else 'undefined-lookup))) ;...

Both your examples are tail call optimized in the sense that, an interpreter can look at it and see that in the first case the cond is always executed as the last expression of this function call. This means that it does not keep stack. In your second example it...

directory-list returns relative paths by default, which are later implicitly resolved with respect to the (current-directory), which might be different from the directory you passed to directory-list. Kind of like this: ~ $ ls dir file1 subdir2 ~ $ cat file1 cat: file1: No such file or directory From the...

Works fine for me. Compiled Chicken with the same version on Ubuntu, down to the specific revision. Your call history looks very strange. More specifically: <eval> [append] (reverse target) <syntax> (print (exponent 5 2)) The [append] (reverse target) portion looks weird. Your exponent function (as described) does not call that....

Here's one possible solution, using built-in procedures in Racket: (define (split mylist num) (cons (takef mylist (lambda (n) (<= n num))) (dropf mylist (lambda (n) (<= n num))))) For example: (split '(1 2 3 4) 3) => '((1 2 3) 4) (split '(1 2 3 4 5) 3) => '((1...

Racket pairs are different from Scheme pairs since Racket pairs are immutable while Scheme pairs are not. As far as I know, there is no way to check for Racket's immutable lists in pure RnRS Scheme. However, it is possible to use Scheme's mutable lists in Racket (though of course...

function,lambda,nested,scheme,sicp

You're correct that only the outer lambda form is applied to the argument 5. Then it returns its body with a replaced with 5, so it would return (lambda (b) (+ (sqrt 5) (sqrt b))) which is itself a function. This could later be applied to another argument, to produce...

This is a HW assignment so I won't give you code. Your problem is that multiplying (modulo n 10) by 10 doesn't get you to the position you need to be in. Consider (reverse-digits 123): (reverse-digits 123) (+ 30 (reverse-digits 12)) (+ 30 (+ 20 (reverse-digits 1))) (+ 30 (+...

If you want to run .scm source file as a command line program you have to add at the head of your file: #!/usr/bin/guile -s !# where you must specify proper path to you guile executable. You can find location of guile by which guile and you will get something...

It is equivalent to: (define (reverse-nested lst) (cond ((not (pair? lst)) lst) (else (reverse (map reverse-nested lst))))) ...

Just do a substitution: (p-car (p-cons "foo" "bar")) ;substituting p-cons: (p-car (lambda (proc) (proc "foo" "bar"))) ;substituting p-car: ((lambda (proc) (proc "foo" "bar")) (lambda (p q) p)) ((lambda (p q) p) "foo" "bar") "foo" And similarly for p-cdr. Essentially p-cons just creates a lambda which expects a procedure which will...

define in Scheme is not easily implemented in Common Lisp. It's not easily implemented in Scheme either. It's transformation is different in different scopes: (define test value) ; defines test, value can be anything even (lambda ..) which makes a procedur object (define (test arg ...) body ...) ; defines...

When you start with n being 2, you then call (repeated f (- 1 2)). (- 1 2) is -1, which is not equal to 1, so it continues with (repeated f (- 1 -1)). (- 1 -1) is 2, so you call (repeated f 2) again and you have...

In ((cdr X)) you will get an error, if X doesn't evaluate to a pair where the cdr is a thunk. In your first expression, the initial value of X is (cons 2 (lambda () (cc #f))). So everything is fine. However when you invoke the thunk, the expression (cc...

#lang racket (define list1 '("xx1" "xx2" "xx3" "xx4" "xx5")) (define list2 '("xx2" "xx4" "xx5")) (for/list ([x (in-list list1)] #:unless (member x list2)) x) Result: '("xx1" "xx3") ...

With the approach you're taking, just map a function that checks whether the item meets the criteria: (map (lambda (x) (if (criteria? x) (create-evaluation-link x))) parse) However, as others have noted in the comments, using map to do imperative work may be a place where some other approach might be...

Bear in mind that (cdr (cdr ...)) is returning a list (not an element!), so pair? will return true if the list has enough elements (three or more). Perhaps you were aiming for something like this? (define (multiplicand p) (if (null? (cdddr p)) ; assuming list has at least 3...

Another example would be helpful. Going with the assumption that all the elements of a member list are equivalent to each other, this might suffice: (define (partition lol) ; lol, list of lists (apply append (map (lambda (liszt) (apply append (map (lambda (elem) (map (lambda (other) (list elem other)) liszt))...

loops,recursion,lambda,scheme,r5rs

To see what happens when ((lambda (x) (x x)) (lambda (x) (x x)) is evaluated use the stepper in DrRacket. It can show you the steps an evaluation takes. Write your expression in the definition window of DrRacket. Then choose the teaching language "Intermediate Student with lambda". Then click the...

I would just use except-in (or perhaps rename-in) to avoid the few identifiers that don't work in both typed and untyped programs. Like this modification of Greg's program: #lang racket/base (require (except-in typed/racket struct)) (struct point (x y)) (let ([x 'hello]) (with-type #:result String #:freevars ([x String]) (string-append x ",...

Of course we can use an if inside a lambda, in fact, any valid expression can go inside a lambda. There are more serious errors in your code: There are additional (and unnecessary) parentheses surrounding the innermost if expression. Scheme will interpret them as a function application, and that's not...

You're close, but not quite right. It'll be more clear if we build the list structure explicitly using cons; this is more like it: (cons 'a (cons (cons (cons 'f (cons 'b 'c)) (cons 'g (cons 'h '()))) (cons 'e '()))) => '(a ((f b . c) g h) e)...

This code rewrites numerosRandom to separate generation of random numbers from their display. It also returns the random numbers as a list. The beginning of numerosRandom is unchanged. (define (numerosRandom) (define contador 1) Now circlo only does one thing. It creates a list of random numbers. Now circlo accepts one...

You can try to use begin in an if statement. like so: (if (something) (begin (foo) (bar))) ...

An Emacs buffer is not a real terminal, and rlwrap will not run in it. However, this is no tragedy: almost all of rlwraps goodness can be had directly from Emacs (you could use one of the existing scheme modes, or even Emacs-gosh-mode) If you insist, Emacs can provide a...

The problem is that if (reverse (cdr lat)) returns a list eg (3 2) then (cons '(3 2) (1)) turns into ((3 2) 1). A classical way to do this would be to make a local procedure that takes an accumulator as well as the argument of the global procedure....

This is the type I would assign to break: (require/typed (only-in srfi/1 break) [break (All [T] (-> (T -> Any) (Listof T) (Values (Listof T) (Listof T))))]) The predicate function can return anything. If it returns #f, it will be treated as falsy, and any other result will be treated...

Here's my version: #lang htdp/isl (define (list-prefix? lhs rhs) (or (empty? lhs) (and (not (empty? rhs)) (eqv? (first lhs) (first rhs)) (list-prefix? (rest lhs) (rest rhs))))) (define (list-overlap lhs rhs) (if (list-prefix? lhs rhs) rhs (cons (first lhs) (list-overlap (rest lhs) rhs)))) Note that list-prefix? returns true if lhs is...

cond is a special form and an in place replacement for nested if. It seems to me that you didn't intend to check if car was true so that a would always be the result so I guess that what you actually wanted to use was cons instead: (define (intersection...

list,recursion,functional-programming,scheme

Here's my version (note that I've changed it to return the result as a single dotted pair, rather than a list with two elements†): (define (min/max lst) (if (empty? lst) #f (let ((next (min/max (cdr lst)))) (define cur (car lst)) (if (not next) (cons cur cur) (cons (min (car next)...

You're right about something - evaluating code from a string is a bad code smell… maybe there's a better way to do what you want to accomplish. Anyway, here's a possible solution: (define-namespace-anchor a) (define ns (namespace-anchor->namespace a)) (define (eval-string str) (eval (call-with-input-string str read) ns)) It works as requested...

You forgot to call reduct again after adding. Here's the fixed version: (define (reduct n) (if (< n 10) n (reduct (+ (modulo n 10) (reduct (quotient n 10)))))) Note that the inner reduct recursion is actually redundant and can be removed, leaving: (define (reduct n) (if (< n 10)...

Racket actually has a built-in math library, and the math/number-theory module provides a convenient perfect-square function. The documentation for perfect-square describes it as follows: Returns (sqrt m) if m is perfect square, otherwise #f. This, of course, makes implementing your function trivial. You could just do something like this: (require...

Chris is correct. In the event you want to use rest arguments and then use it in recursion you should consider wrapping it in a named let or make a local helper procedure. (define (zip . args) (let aux ((args args)) (if (ormap null? args) '() (cons (map car args)...

There are a few different issues here. As Oscar Lopez points out, one is an indirection, and one is a wrapper. Christophe De Troyer did some timing and noted that without optimization, the indirection can take twice as much time as the indirection. That's because the alias makes the value...

functional-programming,scheme,closures,sicp

You're right; this text is not referring to "closures"--an implementation strategy to ensure that functions-as-values refer correctly to lexical bindings--but more generally to the mathematical notion of "closure", as for instance in the statement "the integers are closed under the addition operation". That is: applying the operation to any two...

count,functional-programming,scheme,racket,mud

Change the (eq? (user-attribute 'gem) 1) to this, instead: (>= (user-attribute 'gem) 1) By the way, don't use eq? to compare numbers. Use = or (if you need to compare against generic objects) eqv?. The OP asked how to suppress the bribe message if there are no gems. Here's how...

scheme,racket,continuations,delimited-continuations

What is a prompt, conceptually? Scheme in general has the idea of continuations, but Racket extends this with the idea of delimited continuations. The idea of a continuation is that it captures the remaining computation left to be evaluated. I will not attempt to explain continuations in general, since that...

function,lambda,functional-programming,scheme

Here is one way you can calculate the numbers by sending in only 5 arguments instead of 6: (define sum (lambda (L skip) ;stores yourList and the number you want to skip (define loop (lambda (L L2 total) ;yourList, (1,5,10...) list, running total (cond ((null? L) (list total)) ;print the...

You're very close, and you're on the right track thinking about list*. In fact, replacing list with list* in your attempt yields this program, which is almost exactly correct: (define (likenate lst) (cond [(empty? lst) '()] [else (list* (first lst) 'like (likenate (rest lst)))])) You can think of list* as...

From comp.lang.scheme in 1999: https://groups.google.com/d/msg/comp.lang.scheme/Fysq_Wplxsw/awxEZ_uxW20J From: mad...@news.ens.fr (David Madore) Subject: call/cc mind-boggler Date: 1999/06/24 Message-ID: <[email protected]>#1/1 X-Deja-AN: 493362808 Organization: Ecole normale superieure Newsgroups: comp.lang.scheme I sumbled (accidentally as it were) upon the following Scheme program: (let* ((yin ((lambda (foo) (newline) foo) (call/cc (lambda (bar) bar)))) (yang ((lambda (foo) (write-char #\*)...

A straight-forward version without any higher order functions or any bells and whistles at all - very beginner-level, I hope: It's most common to recurse on the lists' structure, not their size, so we'll do that. This can seem uncomfortable at first if you're used to writing for-loops, but most...

The parentheses are incorrect in the first case, and in the last case you forgot to write the else. Also, the second case is incorrect; this is what I mean: (define (remove lst) (cond ((null? lst) '()) ((null? (cdr lst)) lst) ((equal? (car lst) (car (cdr lst))) (remove (cdr lst)))...

Pairwise Disjoint As far as I know, the only way to check if a set is pairwise disjoint is to enumerate every possible pair and check for matches. Note that this does not follow the racket syntax, but the meaning should still be pretty clear. (define (contains-match? x lst) (cond...

In general, the idea of mapping is that for any list (define lst (list a b c d ... )) and function f, the value of (map f lst) is the same as the value of (list (f a) (f b) (f c) (f d) ...). Let's simulate evaluation as...

functional-programming,scheme,racket

The "normal" way of getting specific element based on their values is to use filter with a suitable predicate. Something along these lines: (define (may? str) (string=? "may" (substring str 0 3))) (define (only-may ls) (filter (lambda (x) (may? (car x))) ls)) ...

scheme,interpreter,chicken-scheme

In general, the answer is "don't". The way you're supposed to use the REPL is by evaluating piecemeal changes against it, then evaluating a function or two to make sure everything went as expected. Part of this approach is structuring your program so that it can be easily tested in...

No. This SFRI specifically requests that a filter function be added because it is not present in R5RS. There is however a filter function defined in MIT-Scheme, and in R6RS, behaving exactly as one would expect.

MIT/GNU Scheme should start off as minimized. It is just a background console window that starts the editor. You need not pay attention to it (nor can you interact with it). Edwin: *scheme* is the Edwin text editor, which looks to me like some sort of Emacs derivative. It allows...

Nope. In that list, and is not a procedure. It is a symbol. This is due to how quoting works. The expression '(a b c) is effectively the same as (list 'a 'b 'c), so and is literally evaluated as the symbol, 'and. Either explicitly use the list function to...

javascript,arrays,recursion,scheme,the-little-schemer

A list is a nested array of 2 element ['t',['e',['s',['t',null]]]]. Split makes ['t', 'e', 's', 't']. array.shift() mutates. You really should use something like this this instead: function car(cons) { return cons[0]; } function cdr(cons) { return cons[1]; } ...

The main problem here is the last line: else (temp)))))) The parentheses are incorrect here—the else keyword needs to be within the parens. Changing that to this: (else temp)))))) ...fixes the algorithm. You also aren't calling maxmin properly—it needs a list, not a series of parameters. Your final line of...

You can use apply: (apply func '(1 2 3)) ...

I'd write an implementation based on filter from SRFI-1 (as suggested by @Sylwester) and SRFI-26, because I happen to like the cut macro for currying functions. It'll yield a shorter and IMHO clearer answer, just make sure that all the words are in lower (or upper) case: (use-modules (srfi srfi-1)...

The problem is that some sequences are infinite, for example the one given by (in-integers). For a finite sequence you can use: (define (sequence-reverse s) (reverse (sequence->list s))) ...

1e16 is, in Scheme terms, an inexact number (or in more practical terms, a floating-point number). For (double-precision) floating point numbers above 253 (9007199254740992), the ulp is greater than 1, which means changes by 1 are too small to be represented.† 10000000000000000, on the other hand, is an integer. If...

file,scheme,append,r6rs,ironscheme

IronScheme supports R6RS :) file-options are not available on with-output-to-file, so you need to use open-file-output-port. Example (not correct): (let ((p (open-file-output-port "robot-log.txt" (file-options no-create)))) (fprintf p "~a\r\n" whatToWrite) (close-port p)) Update: The above will not work. It seems you might have found a bug in IronScheme. It is not...

I fixed this problem by installing the beignet package from the Arch User Repository. This package conflicted with my installation of libcl, which it also provides. I removed my extraneous libcl with sudo pacman -R -dd libcl to skip dependency checks. After sucessfully installing beignet, raco test --drdr -p opencl...

In this context, "pair" just means a cons pair, such as (5 . 6) or (foo . #t). An example unification between two pairs is: (call/fresh (λ (a) (call/fresh (λ (b) (≡ (cons a b) (cons 5 6)))))) which associates a with 5 and b with 6....

Your let* form is missing the body (the code that uses the bindings). Even if the body simply returns mst, like so: (let* ((ll (ListLink x y)) (in (cog-incoming-set ll)) (mst (get-mst-node in))) mst) ...

Here's my implementation. Note that you need to load SRFI 1, which provides unfold-right: (define letters "ABCDEFGHIJKLMNOPQRSTUVWXYZ") (define (number->letters num) (unfold-right negative? (lambda (i) (string-ref letters (remainder i 26))) (lambda (i) (- (quotient i 26) 1)) num)) (define (number->tag num) (list->string (cons #\M (number->letters num)))) Examples: > (number->tag 0) "MA"...