The 'Bowling Game' Kata in 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 | |
(define LAST-FRAME 10) | |
(define ALL-PINS 10) | |
(define (is-spare? rolls) (= ALL-PINS (+ (first rolls) (second rolls)))) | |
(define (is-strike? rolls) (= ALL-PINS (first rolls))) | |
(define (score-frame frame score rolls) | |
(score-frames (add1 frame) | |
(+ score (first rolls) (second rolls)) | |
(cddr rolls))) | |
(define (score-spare frame score rolls) | |
(score-frames (add1 frame) | |
(+ score ALL-PINS (third rolls)) | |
(cddr rolls))) | |
(define (score-strike frame score rolls) | |
(score-frames (add1 frame) | |
(+ score ALL-PINS (second rolls) (third rolls)) | |
(cdr rolls))) | |
(define (score-frames frame score rolls) | |
(cond | |
[(= LAST-FRAME frame) score] | |
[(is-strike? rolls) (score-strike frame score rolls)] | |
[(is-spare? rolls) (score-spare frame score rolls)] | |
[else (score-frame frame score rolls)])) | |
(define (bowl rolls) (score-frames 0 0 rolls)) | |
(require rackunit) | |
(define (many times pins) (for/list ([i (in-range times)]) pins)) | |
(define (gutter n) (many n 0)) | |
(define (spare) (many 2 5)) | |
(define (strike) (list ALL-PINS)) | |
(define (frame a b) (list a b)) | |
(test-equal? "gutter game" (bowl (gutter 20)) 0) | |
(test-equal? "all ones" (bowl (many 20 1)) 20) | |
(test-equal? "spare" (bowl (append (spare) (frame 3 1) (gutter 16))) 17) | |
(test-equal? "strike" (bowl (append (strike) (frame 3 4) (gutter 16))) 24) | |
(test-equal? "perfection" (bowl (many 12 ALL-PINS)) 300) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment