Skip to content

Instantly share code, notes, and snippets.

@weakish
Created July 23, 2017 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weakish/24f076627a88ae1b375baca6fded57c9 to your computer and use it in GitHub Desktop.
Save weakish/24f076627a88ae1b375baca6fded57c9 to your computer and use it in GitHub Desktop.
htdp 2e. exercise 125 #racket
#lang racket
(require lang/htdp-beginner)
; Htdp 2e. Exercise 125
;
; A List-of-amounts is one of:
; – empty
; – (cons PositiveNumber List-of-amounts)
; interp. a List-of-amounts represents some amounts of money
; List -> Boolean
(check-expect (List-of-amounts? empty) true)
(check-expect (List-of-amounts? (cons 1 empty)) true)
(check-expect (List-of-amounts? 1) false)
(check-expect (List-of-amounts? "1") false)
(check-expect (List-of-amounts? (cons -1 (cons 1 empty))) false)
(check-expect (List-of-amounts? (cons 1 (cons -1 empty))) false)
(define (List-of-amounts? l) (cond
[(empty? l) true]
[(not (cons? l)) false]
[(and (> (first l) 0) (List-of-amounts? (rest l))) true]
[else false]))
; List -> Number-Or-False
; caculater sum of List-of-amounts
(check-expect (sum (cons 6 empty)) 6)
(check-expect (sum (cons 2 (cons 3 empty))) 5)
(check-expect (sum (cons -1 empty)) false)
(check-expect (sum empty) 0)
(define (sum l) (cond
[(empty? l) 0]
[(not (List-of-amounts? l)) false]
[else (+ (first l) (sum (rest l)))]))
; License: 0BSD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment