Module 1

Functions

$$f(t) = 30 - 1/2 * 9.8 * t^2$$

becomes

;; height-above-ground : Number -> Number
;; OR: height-above-ground : Time -> Position
(define (height-above-ground time)
  (- 30 (* 0.5 9.8 time time)))

Documentation of functions

  • Purpose
    • Describes the Semantics
    • One sentence, terse description of the function
    • Should not paraphrase the code
  • Signature
    • function-name : ParamType ParamType ... -> OutputType
    • Shows expected inputs and outputs

Defining functions

(define (FUNCTION-NAME ARG-NAME ...)
  FUNCTION-BODY)

; Call function
(FUNCTION-NAME ARG)

Booleans

  • #true or #false
  • Suffix function with ?
  • (=? VAR 100) will return a boolean

Predicates

  • Functions that return a boolean are predicates
  • They end in a ?
  • Examples include
    • number?
    • string?
    • image?
    • boolean?

Conditions

(cond
  [test-1 answer-2]
  [test-2 answer-2]
  ...
  [else answer-x])
(cond [(< 3 0) "hi"][(< 4 0) "bye"])
> cond: all question results were false
  • Program stopped if all conditions are false
  • If conditions overlap, first one is executed (order matters)

Examples

Example: drawing the sky, sun, and grass

(require 2htdp/image)

(define SUN (circle 25 "solid" "yellow"))
(define SKY (rectangle 300 200 "solid" "light blue"))
(define GRASS (rectangle 300 20 "solid" "forest green"))

(define BACKGROUND (above SKY GRASS))

(place-image SUN 50 50 BACKGROUND)

Example: eclipse

(require 2htdp/image)
(require 2htdp/universe)

(define SUN (circle 25 "solid" "yellow"))
(define MOON (circle 25 "solid" "gray"))
(define SKY (square 200 "solid" "blue"))

(define SUN-IN-SKY (place-image SUN 100 100 SKY))

;; eclipse : Number -> Image
(define (eclipse moon-position)
  (place-image MOON moon-position 100 SUN-IN-SKY))

;; Run (animate eclipse)

Example: displaying the last position of the moon

(string-append "The last position of the moon was " (number->string (animate eclipse)))
> "The last position of the moon was 47"