concept guess in category idris

appears as: guess, guess, guesses
Type-Driven Development with Idris

This is an excerpt from Manning's book Type-Driven Development with Idris.

  • Write a function that implements a simple “guess the number” game. It should have the following type:
    guess : (target : Nat) -> IO ()
    Here, target is the number to be guessed, and guess should behave as follows:
    • Repeatedly ask the user to guess a number, and display whether the guess is too high, too low, or correct.
    • When the guess is correct, exit.
    Ideally, guess will also report an error message if the input is invalid (for example, if it contains characters that are not digits or are out of range).
  • guess : (target : Nat) -> IO ()
  • Implement a main function that chooses a random number between 1 and 100 and then calls guess. Hint: As a source of random numbers, you could use time : IO Integer, defined in the System module.
  • Extend guess so that it counts the number of guesses the user has taken and displays that number before the input is read. Hint: Refine the type of guess to the following:
    guess : (target : Nat) -> (guesses : Nat) -> IO ()
  • Then, instead of using getLine, write a readGuess function that returns the user’s guess, along with an instance of a predicate that guarantees the user’s guess is a valid input:

    9.2.4. Processing a guess

    Processing a guess will return a game state with one type if the guess is correct, and a different type if the guess is incorrect. You can use the Either generic type to represent this. Remember that Either is a generic type defined in the Prelude that carries a value of two possible types:

    data Either a b = Left a | Right b

    Either is often used to represent the result of a computation that might fail, carrying information about the error if it does fail. By convention, we use Left for the error case and Right for the success case.[1] You can think of an incorrect guess as being the error case, so the next listing shows the type you’ll use for a function that processes a guess.

    Figure 14.5. State transition diagram for Hangman. The Running state also holds the number of letters and guesses remaining. Won requires the number of letters to be zero, and Lost requires the number of guesses to be zero.