guess

examples/guess.omg

examples/guess.omg55 lines
1{-  A guessing game: an interactive program with a loop.
2
3        omegyu run examples/guess.omg
4
5    `IO/loop` repeats a step for as long as it returns a new state (`Some`);
6    it is the only way to write a program that runs for an unbounded time.
7-}
8
9let Console = std:IO
10
11let Number = std:Natural
12
13let secret = 42
14
15-- One round: read a guess, answer, and say whether to go on.  The state is
16-- the number of guesses so far.
17let round
18    : Natural -> IO (Optional Natural)
19    = \guesses ->
20        do {
21          Console.putStr "Your guess: ";
22          line <- Console.getLine;
23          merge
24            { -- The end of the input ends the game.
25              None = do { Console.putStrLn ""; IO/pure (None Natural) }
26            , Some =
27                \(text : Text) ->
28                  merge
29                    { None = do { Console.putStrLn "That is not a number."; IO/pure (Some guesses) }
30                    , Some =
31                        \(guess : Natural) ->
32                          if Number.equal guess secret
33                          then do {
34                                 Console.putStrLn
35                                   "Yes! That took ${Natural/show (guesses + 1)} guesses.";
36                                 IO/pure (None Natural)
37                               }
38                          else do {
39                                 Console.putStrLn
40                                   (if Number.lessThan guess secret
41                                    then "Too small."
42                                    else "Too large.");
43                                 IO/pure (Some (guesses + 1))
44                               }
45                    }
46                    (Natural/parse text)
47            }
48            line
49        }
50
51in  do {
52      Console.putStrLn "I am thinking of a number between 1 and 100.";
53      _ <- Console.loop 0 round;
54      IO/pure {=}
55    }
Your result
Complete file: examples/guess.omg · with imports