Skip to content

Instantly share code, notes, and snippets.

@nafg
Created February 27, 2017 06:30
Show Gist options
  • Save nafg/edd772f7cd47500059b373ce7434877e to your computer and use it in GitHub Desktop.
Save nafg/edd772f7cd47500059b373ce7434877e to your computer and use it in GitHub Desktop.
package twentyquestions
import scala.io.StdIn
sealed trait Step
case class Question(text: String, yes: Step, no: Step) extends Step
case class Guess(text: String) extends Step
object Main {
val initialModel =
Question(
text = "Is it an animal?",
yes = Guess("an elephant"),
no = Guess("a frying pan")
)
def runStep(step: Step): Step = step match {
case Question(questionText, yes, no) =>
StdIn.readLine(questionText + " ").toLowerCase match {
case "yes" =>
val newYesBranch = runStep(yes)
Question(questionText, newYesBranch, no)
case "no" =>
val newNoBranch = runStep(no)
Question(questionText, yes, newNoBranch)
}
case Guess(guessText) =>
StdIn.readLine("Is it " + guessText + "? ").toLowerCase match {
case "yes" =>
println("I won!")
step
case "no" =>
val answer = StdIn.readLine("I give up. What were you thinking of? ")
val newQuestionText =
StdIn.readLine(
"Enter a question that the answer is 'yes' for " + answer + " and 'no' for " + guessText + ". "
)
Question(text = newQuestionText, yes = Guess(answer), no = Guess(guessText))
}
}
def main(args: Array[String]): Unit = {
def loop(model: Step): Unit = {
val result = runStep(model)
StdIn.readLine("Do you want to play again? ").toLowerCase match {
case "no" =>
case "yes" => loop(result)
}
}
loop(initialModel)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment