1. Higher-order functions, again!
Here are the signatures of some of the higher-order functions provided by DrRacket.
;; map : [X -> Y] List<X> -> List<Y>
;; andmap: [X -> Boolean] List<X> -> Boolean
;; ormap: [X -> Boolean] List<X> -> Boolean
;; foldr: [X Y -> Y] Y List<X> -> Y
;; foldl: [X Y -> Y] Y List<X> -> Y
You are provided with the following Data Definition
;; An Atom is one of:
;; - Number
;; - Boolean
;; - String
;; - Symbol
Solve the following questions using higher order functions, local and/or lambda
2. Generic Trees
A friend is working on an assignment that asks them to generalize over trees. They already have examples of tree data definitions
(define-struct node (val kids))
;; A Node<X> is a (make-node X LoF<X>)
;; INTERP: represents a node in a tree
;; An ST is one of
;; - empty
;; - Node<String>
;; An IT is one of
;; - empty
;; - Node<Integer>
Your friend is having problems generalizing over these data definitions.
Now your friend is asked to generalize over functions of ST
and IT
.
3. Dealing with mouse input in an animation
DrRacket’s big-bang
allows programmers to detect mouse operations. The way that we handle mouse events is similar to the way that we
handle key events. big-bang
has a clause named on-mouse
.
The on-mouse
clause must be given a function with the signature
;; World Integer Integer MouseEvent -> World
;; A MouseEvent is one of
;; - "button-down"
;; - "button-up"
;; - "drag"
;; - "move"
;; - "enter"
;; - "leave"
The documentation on MouseEvent has more information for each event.
|
The function given to on-mouse
needs to accept a the current World
the x and y-coordinate on the canvas where the mouse might have been clicked and a MouseEvent
. The function needs to then return the new World
after taking into account the mouse event that just occurred.
Here is a small program that you can run and play around with. Clicking inside the canvas should move the red dot to where you click and display the text pressed button
. If you click the mouse button and keep it pressed and then move the mouse the red dot should follow your mouse and display the text press and drag
.
(require 2htdp/image)
(require 2htdp/universe)
(define BG (empty-scene 500 500))
(define MARK (circle 15 'solid 'red))
(define-struct world (mouse-location message))
(define (draw w)
(place-image
(text (world-message w) 20 "blue")
250
20
(place-image MARK
(posn-x (world-mouse-location w))
(posn-y (world-mouse-location w))
BG)))
(define (tock w)
w)
(define (handle-key w key-event)
w)
(define (handle-mouse w x y mouse-event)
(cond
[(string=? "button-down" mouse-event)
(make-world (make-posn x y) "pressed button")]
[(string=? "drag" mouse-event)
(make-world (make-posn x y) "press and drag")]
[else (make-world (world-mouse-location w) "")]))
(define (start world)
(big-bang world
(on-tick tock)
(on-key handle-key)
(on-mouse handle-mouse)
(to-draw draw)))