Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created January 16, 2021 20:06
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 mdwhatcott/7f686303be9e9e1dbe42891814e15bb2 to your computer and use it in GitHub Desktop.
Save mdwhatcott/7f686303be9e9e1dbe42891814e15bb2 to your computer and use it in GitHub Desktop.
The 'Bowling Game' Kata in Racket
#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