UNB/ CS/ David Bremner/ teaching/ cs3613/ tutorials/ CS3613 Tutorial 2

Part 1

For each of the following code samples, add sufficient test forms to get full coverage

Sample 1

#lang plai-typed
(define (digit-num n)
  (cond [(<= n 9)    (some 1)]
        [(<= n 99)   (some 2)]
        [(<= n 999)  (some 3)]
        [(<= n 9999) (some 4)]
        [else        (none)]))

Sample 2

#lang plai-typed
(define (helper n acc)
  (if (zero? n)
    (helper (- n 1) (* acc n))))

(define (fact n)
  (helper n 1))

Sample 3

For the parser example, you'll need to peruse the documentation on expressions to figure out how to test for errors. You may also find the S-expression documentation helpful in constructing test input.

#lang plai-typed
(define-type AE
  [Num (n : number)]
  [Add (l : AE) (r : AE)]
  [Sub (l : AE) (r : AE)])
(define (parse [s : s-expression])
     [(s-exp-number? s) (Num (s-exp->number s))]
     [(s-exp-list? s)
      (let* ([sl (s-exp->list s)]
             [op (s-exp->symbol (first sl))]
             [left (second sl)]
             [right (third sl)])
        (case op
          [(+) (Add (parse left) (parse right))]
          [(-) (Sub (parse left) (parse right))]))]
     [else (error 'parse-sexpr "bad syntax")]))

Part 2

Sample 3 has several bugs, namely syntax errors that crash the parser, rather than generate error messages about the input. Correct at least one of these bugs, and add a suitable test.