scheme,lisp,racket , Racket: using big bang and on-click

Racket: using big bang and on-click


Tag: scheme,lisp,racket

I've somehow been able to draw a small basic image in racket (a house). Now, what I'm stuck with is, using big-bang to draw the image -- and then being able to click the roof of the house and have it change to another color. This is what I have so far:

#lang racket
(require 2htdp/image)
(require 2htdp/universe)

(text "---Small Shack---" 18 "brown")

(define door (rectangle 30 50 "solid" "white"))

(define shack (above (triangle 100 "solid" "red")
                     (rectangle 120 80 "solid" "grey")))

(define doorhandle (overlay/align "right" "center" (circle 5 "solid" "blue") door))

(define house-view (overlay/align "center" "bottom" doorhandle shack))


I've tried a million different things to get it to work with big-bang but nothing worked. Any help getting big-bang and it changing color of the roof when clicked?


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:

  (λ (state)
    (text "---Small Shack---" 18 "brown")
    (define door (rectangle 30 50 "solid" "white"))
    (define shack (above (triangle 100 "solid" "red")
                         (rectangle 120 80 "solid" "grey")))
    (define doorhandle (overlay/align "right" "center" (circle 5 "solid" "blue") door))
    (define house-view (overlay/align "center" "bottom" doorhandle shack))

This will display your house as the result of each draw call. You'll also need some way to manage your world state. The conventional way to do this is by using a struct.

(struct world (roof-color))

The first parameter you provide to big-bang is the initial state, so we should initialize the state to use "red" as the roof color. Then we can use the current state's color in our to-draw handler:

 (world "red")
  (λ (state)
    (text "---Small Shack---" 18 "brown")
    (define door (rectangle 30 50 "solid" "white"))
    (define shack (above (triangle 100 "solid" (world-roof-color state))
                         (rectangle 120 80 "solid" "grey")))
    (define doorhandle (overlay/align "right" "center" (circle 5 "solid" "blue") door))
    (define house-view (overlay/align "center" "bottom" doorhandle shack))

Finally, you can implement a on-mouse clause to handle mouse clicks. Here's a simple implementation that makes the roof green when the user clicks.

 (world "red")

  (λ (state x y event)
    (case event
       (world "green")]
      [else state])))

  (λ (state)
    (text "---Small Shack---" 18 "brown")
    (define door (rectangle 30 50 "solid" "white"))
    (define shack (above (triangle 100 "solid" (world-roof-color state))
                         (rectangle 120 80 "solid" "grey")))
    (define doorhandle (overlay/align "right" "center" (circle 5 "solid" "blue") door))
    (define house-view (overlay/align "center" "bottom" doorhandle shack))

For more information, see the relevant documentation in the HtDP 2e section of the Racket documentation. You should be able to figure out how to tweak this to your needs.


Exceed evaluation depth when forward function in Emacs Lisp

Here is just a simplified code snipped I have not managed to work. I do not understand what is wrong. (defun enumerate-indicies (func) (let ((index 0)) (while (< index 5) (funcall func index) (setq index (1+ index))))) (defun enumerate-multiplied-indicies (func) (enumerate-indicies #'(lambda (index) (funcall func (* 10 index))))) The following...

Modify list and return it inside a function in lisp

(defun testthis (node index newvalue) (set-nth node index newvalue) node ) I would like to modify the nth element of a list in a function and then returns this list to save the modification performed. How can I do a such function in lisp?...

Defining cons, car and cdr with lambda - how does it work? [duplicate]

This question already has an answer here: Use of lambda for cons/car/cdr definition in SICP 2 answers I can't seem to explain how this definition of cons, car and cdr works: (define (p-cons x y) (lambda (proc) (proc x y))) (define (p-car proc) (proc (lambda (p q) p))) (define...

How to use a parameter in a macro call?

I have defined the following simple macro: (defmacro define-class (class-name) `(defclass ,class-name ()())) And now I want to use it in the following function: (defun create-data (mode) (define-class mode)) After compiling the last function I get the following message, the variable MODE is defined but never used. And when I...

Writing a While Loop in Scheme

I am trying to implement a while loop using recursion with lambda, but I just don't understand how to do it. I am supposed to start with this lambda expression: ((lambda (x) (x x)) (lambda (x) (x x)) My first question is why does this cause 'eternal' recursion? I try...

No-argument (and) returns t

Both CL and Scheme define (and) to return t (or #t) with no arguments. I'm trying to understand the rationale for this. My naive assumption is that an empty set is false, and passing in zero arguments feels like passing in nothing that can be true. Edit: clojure follows the...

Is there a way to see the body of a lambda in Racket?

Say I have this code: #lang racket (define a ((λ (x) x) ((λ (y) y) (λ (z) ((λ (w) w) z))))) I know intuitively that this lambda expression is (extensionally) equal to (λ (z) z) My question is if there is a way to print out the body of a...

Insertion into a list doesn't reflect outside function whereas deletion does?

I am new to Lisp. Deletion of an item in a list by a function gets reflected outside the function but insertion doesn't. How can I do the same for insertion? For example (defun test (a b) (delete 1 a) (delete 5 b) (append '(5) b) (member '5 b)) (setq...

Any history background about the “yin-yang puzzle” in detail?

There are quite a few questions about the "yin-yang puzzle" already in Stackoverflow: How does the yin yang puzzle work? (I assume this is the first one) Haskell (this is my question) C# 5.0 Typed languages ... (there could be something I didn't find yet) I was wondering when and...

How to use FFI:def-call-in in clisp

I have figured out how to make use of shared objects created from C code into Clisp using FFI:def-call-out but I am not able to figure out how to use FFI:Def-call-in. I don't know the process and actually I am confused if clisp will also create some .so file that...

Returning an element and then deleting the element from a list in Scheme

I have a list in Scheme which contains numbers. I wrote a function that takes as input one number and a list of objects and checks if the confidence value of the object matches the number. Once I get the object whose confidence values matches the given number, I want...

Get element from list of list in lisp

I am a beginner with lisp. I manipulate list of list: ((name1, second) (name2, second2)) The goal of my function is to get the second element of the list that have name as it first node. For example: my list is: ((name1, second1) (name2, second2)) getelement list name1 should return...

Char Comparison in Common Lisp

How can i compare characters with Common Lisp? I have google it and found out that there are some functions to do the comparison, like char=, char/=, char<, char>, char<=, and char>=. But, i can't use all of the functions just like: (char= 'a 'a) (char< 'a 'b) If i...

How would I make this Racket code DRYer?

I'm porting a Python script to Racket as a learning experience, and I have this function: (define (check-status) (define git [find-executable-path "git"]) (define-values (ckot out in err) (subprocess #f #f #f git "checkout" "-q" "master")) (define-values (local lout lin lerr) (subprocess #f #f #f git "rev-parse" "@")) (define-values (remote rout...

If strings are vectors, why are they immutable?

if strings are vectors of characters, and a vector's elements can be accessed using elt, and elt is setf-able - then why are strings immutable?

Value from binding in LFE interpreter using Erlang

I'd like to use Lisp Flavored Erlang as a scripting extension language for an Erlang application. If you want, in a similar way GNU Emacs is configured and extended via Emacs Lisp. I know that the argument is wide and structured; but in the specific case of this question I'd...

How to get only specific elements of list in racket

Input: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73) ("june 101" 55 55) ("june 104" 55 54) ("aug 201" 220 220)) Desired output: '(("may 001" 75 72) ("may 002" 75 75) ("may 003" 70 73)) How do I achieve this? I only want the may terms....

Append string to existing textfile in IronScheme

We are trying to construct a log file using IronScheme, and we have written a code for it using racket. It works fine in racket, but IronScheme throws an error. This is what we have so far: (define write-to-log (lambda(whatToWrite) (with-output-to-file "robot-log.txt" (lambda () (printf (string-append whatToWrite "\r\n" ))) #:exists...

Translate Scheme closure-defining function into Haskell

The following procedure, written in Scheme, (define (eat xs) (lambda (x) (if (eq? x 'vomit) (reverse xs) (eat (cons x xs))))) can be called in the following way: > eat #{procedure 9165 eat} > (eat '()) #{procedure 9166 (unnamed in eat)} > ((eat '()) 1) #{procedure 9166 (unnamed in eat)}...

How would I get the min/max of a list using a key

I currently have a list of objects, each containing a certain attribute. I would like to get the element of the list with the min attribute value. Is there a concise way of doing this? The python equivalent would be something like: min(d, key=d.get) Is there a way of getting...

Accessing call stack depth in Scheme

In order to demonstrate the effectiveness of tail recursion, I would like a way to access the depth of the call stack dynamically in Scheme. Is there a way to do this? If not, is there a way to do this in other major functional languages (OCaml, Haskell, etc.)?...

Scheme several actions if an if-statement proves true

The way I understand a scheme if-statement is that the first condition is when the if-statement is true, and the second statement is when it is false. What if I want several conditions for when the statement proves true? An example: (if (= a b) (set! ([a 2])) // This...

Structuring large Lisp applications

I am currently trying to wrap my head around packages, systems & co. I now have read Packages, systems, modules, libraries - WTF? a few times, and I think I'm still having difficulties to get it right. If I simply want to split a Lisp source file into two files,...

How to create a list of sublists in Lisp without map?

I'm trying to make a function that creates a list of all sublists in the given list. What I mean is, when I've got a list: (4 (a g b) g (1 2 3) g (4 5 6)) I want a list: ((a g b) (1 2 3) (4 5...

“Mapping” Little Schemer to coderbyte challenge: Capitalize

After studying most of The Little Schemer, I've been trying my hand at some recursive solutions to Coderbyte challenges. After some fiddling I threw in cons and thought my upperConsIt would work to look through an array, find all of the instances of a particular letter and capitalize each. Ultimately,...

Understanding “let” expression in LISP

I am extremely new to lisp, had previous experience with functional programming (Haskell, SML). Why is this code returning 14, and not 10 (ie. 1 + 2y + 3 + 1)? (defvar x 1) (defun g (z) (+ x z)) (defun f (y) (+ (g 1) (let ((x (+ y...

how to change the value of sp-navigate-reindent-after-up in smartparens

I want to change the default behavior of smartparens to remove the whitespace before the close delimiter. I mean, when I type ) after (a b c |, I hope the final result is (a b c)|. Here, the | is cursor. I searched the documentation of smartparens, and find...

require/typed contract in racket fails

I've tried looking at the docs but i can't find an example that i can use for my case. I need to import break from srfi/1. Here's my attempt. The example works in #lang racket. #lang typed/racket (require/typed (only-in srfi/1 break) ;[break (All (T) (-> (-> T Boolean) (Listof T)...

Scheme - unpack list's elements into function [duplicate]

This question already has an answer here: How do I pass a list as a list of arguments in racket? 2 answers I have a function which takes an unlimited number of args such as (define (func . args)). Say I have a list '(1 2 3), how do...

Generating n-grams with foldl in Racket

So I'm fiddling with Racket. Recursively generating n-grams from a list of words was pretty straightforward: (define (n-grams-recursive words n) (if (< (length words) n) '() (cons (take words n) (n-grams-recursive (cdr words) n)))) And the iterative version also pretty straightforward: (define (n-grams words n) (define (iter n-grams remaining-words) (if...

LISP: read number from user and commpare with array index

Hello guys I'm new In functional programming Really it is not Clear for me anyone can help me ? My Question just for getting the philosophy of writing on Functional programming language for example how I can write a program in Lisp language for reading the user inputs and compare...

Create lists from lists

I want to write a function which for n arguments will create n lists and each contains n-th element for every argument, for example: (aux '(1 2) '(3 4)) = `((1 3) (2 4)) I wrote such a function: (define (aux . args) (if (null? args) '() (cons (map car...

How is it possible to filter a list of directories via “directory-exists?”?

I recently discovered a strange behaviour of racket: Whenever I try to filter a list of directories created via directory-list my REPL returns me an empty list, but when I try the same with an quasiquoted list my REPL returns a correctly filtered list. My questions is now: Why it's...

Printing ith row jth column value in lisp

I am taking input N as number of rows of a 2D matrix in lisp, where each row can have maximum of 5 elements in it. So i make it like this. Now for eachrow as it can have any number of elements between 0 to 5. So I made...

EVAL/APPLY: too many arguments given to F

Hello why do i get *** - EVAL/APPLY: too many arguments given to F on function call with nested lists parameter. I cannot figure it out, since I passed a simple nested list. (defun f (L) (cond ((NULL l) nil) ((listp (car L)) (append (F(car L))) (F(cdr L) (car (F...

Are Lisp lists always implemented as linked lists under the hood?

Are Lisp lists always implemented as linked lists under the hood? Is this a problem as far as processor caching goes? If so, are there solutions that use more contiguous structures which help caching?...

Implement yield and send in Scheme

I'm trying to port yield and yield from from Python to Scheme. Here is an implementation I've done: (define (coroutine routine) (let ((current routine) (status 'new)) (lambda* (#:optional value) (let ((continuation-and-value (call/cc (lambda (return) (let ((returner (lambda (value) (call/cc (lambda (next) (return (cons next value))))))) (if (equal? status 'new) (begin...

Scheme nested lambda function

I am a beginner in Scheme. I found this question in MIT exam 1 for SICP lecture. What's the value and type for – ((lambda (a) (lambda (b) (+ (sqrt a) (sqrt b)))) 5) I am having a hard time understanding how this function works. I am really confused about...

Racket\Scheme compare and delete unwanted items in a list

I have 2 lists: (Define list1 '("xx1" "xx2" xx3" "xx4" "xx5")) (Define list2 '("xx2" "xx4" "xx5")) the items in the list above are just an example, but either way it will be a string item. What I need to do is compare both lists and remove the items in list1...

lisp remove a the content of one list from another list

I have a list of string like this called F: ("hello word i'am walid" "goodbye madame") => this list contain two elements of string and I have another list call S like this ("word" "madame") => this contain two words now I want to remove the elements of the list...

Return items of a list in Lisp

I have to write a program in Lisp that returns the first item of a list if it contains an even number of elements, and the last if it contains an odd number of elements. I need a little advice on where to start? I don't need whole program.

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

Common Lisp Object System method execution order

I have the following two classes: (defclass person () ()) (defmethod speak ((s person) string) (format t "-A" string)) (defmethod speak :before ((s person) string) (print "Hello! ")) (defmethod speak :after ((s person) string) (print "Have a nice day!")) (defclass speaker (person) ()) (defmethod speak ((i speaker) string) (print "Bonjour!"))...

Backquote String Interpolation

Is it possible to use lisp's macro to do string interpolation? For instance, can I make a macro like this: (defmacro test (a) `",a") So that (test abc) returns "abc" as a string? I could probably cheat by quoting it and turning that quote into a string, but that doesn't...

Using MIT/GNU Scheme

I have downloaded the MIT/GNU Scheme implementation of LISP in order to understand Structure and Interpretation of Computer Programs. However, I am a bit confused about what I am dealing with when I launch the program. When the program is launched, I get two windows: the "MIT/GNU Scheme" window, and...

Invalid specialized parameter in method lambda list

I am trying to write a simple coin flip program in Common Lisp. This is the code I have (defun yn (let ht (random 1) (if (eq ht 1) (princ heads) (princ tails)) ) ) It seems simple enough, but I keep getting the error: "Invalid specialized parameter in method...

How to move a file in Lisp using rename-file

What's the best way to move a file in Lisp in an implementation-independent way? For example I have an image file: (setq oldpath #P"SERVER:PICTURES;TEMP;PHOTO.PNG") and I want to move it out of the TEMP directory into the PICTURES directory. This seems to work: (setq newpath (make-pathname :host (pathname-host oldpath) :directory...

Scheme define-macro and/or define-syntax

I want to create an overloaded Scheme macro for a simple form of polymorphism. That is, a macro smart enough to expand differently when given params of different types, so that (look-up key container) does the "right" thing for different kinds of containers. (define-macro (look-up key container) (cond ((table? container)...

Common Lisp - Giving &rest Lists as Arguments

As a result of musings around an exercism problem, I am trying to write a function that takes an input number and an arbitrary length list of divisors to test, along with the expected divisibility (i.e. remainder 0) as a boolean, returning true if all expectations are met (defaulting to...