Skip to content

Instantly share code, notes, and snippets.

@shaunagm
Last active February 18, 2021 20:38
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 shaunagm/160fb527a96828d89ad045a1d0e5c2b4 to your computer and use it in GitHub Desktop.
Save shaunagm/160fb527a96828d89ad045a1d0e5c2b4 to your computer and use it in GitHub Desktop.
codelibs_iteration_3.rkt
#lang at-exp racket
(require (for-syntax racket/match))
(require (for-syntax racket/syntax))
(define-namespace-anchor anc)
(define ns (namespace-anchor->namespace anc))
; with adjusted macros from text madlibs
(define (ask prompt)
(display prompt)
(read-line))
(define prompt-responses
(make-hash (list )))
; Given variable & prompt, checks if we've recorded a response and prompts as needed. Returns stored/new response.
(define (lookup-or-ask var prompt)
(if (null? (hash-ref prompt-responses var null))
(let ([response (ask prompt)])
(hash-set! prompt-responses var response))
null)
(hash-ref prompt-responses var null))
(define (string->procedure str)
(define operator-hash (hash "+" + "-" - "*" * "/" /))
(hash-ref operator-hash str null))
; Given variable type, get the appropriate function to reformat response
(define (get-reformatter var-type)
(define reformat-hash (hash "number" string->number "operator" string->procedure))
(hash-ref reformat-hash var-type null))
(define-syntax-rule (blank var-type var prompt)
(let ([reformat-function (get-reformatter var-type)])
(reformat-function (lookup-or-ask var prompt))))
;; Code templates
(define-syntax (code-template stx)
(match (syntax->datum stx)
[(list _ template-name operation)
(datum->syntax stx `(define (,(string->symbol template-name)) (eval ,operation ns)))]))
(code-template "add-story" (+ (blank "number" "n1" "A number: ") (blank "number" "n2" "Another number: ")))
(code-template "multiply-story" `(* (blank "number" "n1" "A number: ") (blank "number" "n2" "Another number: ")))
(code-template "change-operator" `((blank "operator" "op1" "Pick an operator (+, -, * or /)") 5 10))
(code-template "do-something-to-10" `((blank "operator" "op1" "Pick an operator (+, -, * or /)") 10 (blank "number" "n1" "A number: ")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment