Created
July 23, 2017 09:42
-
-
Save weakish/24f076627a88ae1b375baca6fded57c9 to your computer and use it in GitHub Desktop.
htdp 2e. exercise 125 #racket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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