Skip to content

Instantly share code, notes, and snippets.

@dyoo
Last active December 11, 2015 23:48
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 dyoo/4678794 to your computer and use it in GitHub Desktop.
Save dyoo/4678794 to your computer and use it in GitHub Desktop.
String expression evaluation example
#lang racket
;; A str-expr is either:
;;
;; 1. a plain string, or
;; 2. (list '+ str-expr str-expr)
;; 3. (list '* number str-expr)
;; evaluate: str-expr -> string
(define (evaluate expr)
(cond
[(string? expr)
expr]
[(eq? (first expr) '+)
(string-append (evaluate (second expr))
(evaluate (third expr)))]
[(eq? (first expr) '*)
(define chunk (evaluate (third expr)))
(define n (second expr))
(apply string-append (for/list ([x n]) chunk))]))
(module+ test
(require rackunit)
(check-equal? (evaluate '"hello")
"hello")
(check-equal? (evaluate '(+ "hello" "world"))
"helloworld")
(check-equal? (evaluate '(+ "rock" (+ (* 5 "p") "aper")))
"rockpppppaper")
(check-equal? (evaluate '(* 3 (+ "scis" "sors")))
"scissorsscissorsscissors"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment