;;A guessing-tree is either: ;; - a string [representing a guess] ;; - (make-branch string guessing-tree guessing-tree) ;; where the string is a yes/no question, the first guessing tree is ;; the tree to use if the answer to the question is "yes", and the ;; second is the tree to use if the answer is "no" (define-struct branch (question yes-tree no-tree)) ;; TEMPLATE: ;;(define (fun-for-guessing-tree gtree) ;; (cond ;; [(string? gtree) ...] ;; [else ;; ... (branch-question gtree) ... ;; ... (fun-for-guessing-tree (branch-yes-tree gtree)) ... ;; ... (fun-for-guessing-tree (branch-no-tree gtree)) ...])) ;; guess : string -> boolean ;; guesses that you're thinking of the given string and lets you ;; responds with whether it's right or wrong. If it's right, returns ;; true; if it's wrong, returns false. (define (guess answer) (ask-yes/no-question (string-append "I guess that you are " answer ". Am I right?"))) ;; play-guessing-game : guessing-tree -> boolean ;; asks you questions until it's able to make a guess, then makes that ;; guess and returns whether it was right or wrong (define (play-one-game t) (cond [(branch? t) (cond [(ask-yes/no-question (branch-question t)) (play-one-game (branch-yes-tree t))] [else (play-one-game (branch-no-tree t))])] [else (guess t)])) (define simpsons (make-branch "Capable of intelligent thought?" (make-branch "Adult?" (make-branch "Jolly?" "Doc" "Prof") "Lisa") "Homer")) ;; tests: (play-one-game "[Something you're not thinking of]") 'shouldbe false (play-one-game "[Something you're thinking of]" 'shouldbe true) (play-one-game (make-branch "[choose yes]" "[something you're thinking of]" "[error]")) 'shouldbe true ;; get-mystery-item : string -> guessing-tree ;; given the incorrect guess the computer made, asks the user for what ;; they were actually thinking of and for a question. It returns a ;; tree whose question is the given question, whose "yes" branch is ;; the new item, and whose "no" branch is the original guess. (define (get-mystery-item wrong-guess) (local ((define right-answer (ask-free-response-question "What were you really thinking of?")) (define q (ask-free-response-question (string-append "What question would differentiate what you were thinking of from " wrong-guess)))) (make-branch q right-answer wrong-guess) )) ;; instruct : tree -> tree ;; plays the guessing game with the given tree and returns a new ;; tree that is: ;; - the same as the old one if the program guessed right ;; - the same as the old one except with the appropriate guess ;; replaced by a branch (define (instruct t) (cond [(branch? t) (cond [(ask-yes/no-question (branch-question t)) (make-branch (branch-question t) (instruct (branch-yes-tree t)) (branch-no-tree t))] [else (make-branch (branch-question t) (branch-yes-tree t) (instruct (branch-no-tree t)))])] [else (cond [(guess t) t] [else (get-mystery-item t)])])) (define (play-learning-game t) (play-learning-game (instruct t))) ;; start the game (play-learning-game "Homer")