Learn

Contents

Interactive programs

An interactive program answers a person as they go: a guess, a move in a game, a sale at a counter. This page builds four of them with elucid8 serve: guess the number, tic-tac-toe for two players, tic-tac-toe against a player that cannot be beaten, and a shop counter. None of them performs an action. What a person does arrives as data, and what they see are values they ask for.

You need what The long-running service and its elucid8 repl teach: a program kept running, rows sent to an input, and queries such as total[t = last]. The four programs, with the scripts that play them, are in the folder interactive/ of the examples' download on the Download page, from 0.23.0; they run with the elucid8 command 0.22.0 or later. Each program below is also shown with a table of moves (a -- table line) and the answers it gives (-- expect), so you can open it in the playground and press Why? beside any answer; a test checks every answer on this page in both of eLucid8's engines, and plays each game through its script.

Moves are data, answers are values

A program has no actions: no "read a line", no "print", no loop that waits. Instead:

So the same rows give the same answers, any number of times, on any machine. Any earlier turn can be asked about, at any moment (hint[t = 0..last] lists every hint so far), and every answer can be explained: Why? in the playground shows exactly which moves it depended on. The only actions are outside the program: the script that sends rows and prints answers.

Against Haskell's IO actions

The Haskell 2010 Report describes Haskell as a purely functional language, and its interactive programs are built from actions whose effects are kept apart by their type. The Report says how (haskell.org/onlinereport/haskell2010):

Guess the number in Haskell is therefore an action that reads, writes and repeats. A sketch, written for this page:

secret :: Int
secret = 37

main :: IO ()
main = do
  putStrLn "I am thinking of a number from 1 to 100."
  loop 1

loop :: Int -> IO ()
loop tries = do
  line <- getLine
  let g = read line :: Int
  if g == secret
    then putStrLn ("correct! You took " ++ show tries ++ " tries.")
    else do
      putStrLn (if g < secret then "higher" else "lower")
      loop (tries + 1)

The guesses are read one at a time by getLine, each answer is written by putStrLn before the next guess is read, and the number of tries is an argument passed from one step of the loop to the next.

eLucid8 has no sequence of actions to write. The same game in eLucid8:

HaskelleLucid8
a guessread by the action getLine, when the program reaches ita row of the input guess, at its turn t
an answerwritten by the action putStrLn, in the program's orderthe value hint[t = …], computed when it is asked for
the state between turnsan argument of the loop (tries)a value over turns (won_before = false fby.t won)
an earlier turngone, unless the program kept itstill there: hint[t = 0] can be asked at any time
the effectsperformed by the runtime, in the order the actions giveoutside the program: the script that sends rows and prints answers

Guess the number, in full

guess/program.el8, with three guesses to try it:

-- Guess the number. Each guess is a row of the input "guess":
-- t is the turn (0, 1, 2, ...), the value is the number guessed.
guess = input("guess", t : inf)

-- The secret number. Change it and run again.
secret = 37

-- Whether the game was already won before this turn.
won_before = false fby.t won

-- Won at this turn or earlier.
won = won_before or guess == secret

-- What the game says after each guess.
hint = if won_before then "already won: start a new game"
       else if guess == secret then "correct!"
       else if guess < secret then "higher"
       else "lower"

-- How many guesses it took (eod until the game is won).
tries = if won and not won_before then #t + 1
        else if won_before then tries[t = #t - 1]
        else eod
-- table guess = t,value; 0,50; 1,25; 2,37
-- expect hint[t = 0] = "lower"
-- expect hint[t = 1] = "higher"
-- expect hint[t = 2] = "correct!"
-- expect hint[t = 3] = "already won: start a new game"
-- expect tries[t = 1] = eod
-- expect tries[t = 2] = 3
-- expect won[t = 1] = false

Open in playground

guess has no end along t (inf): it holds the guesses made so far. hint is a choice by if; at a turn after the game was won it says so, whatever the guess. tries is eod until the game is won, then the turn it was won at plus one, and stays so: after the win, each turn's tries is the one before (tries[t = #t - 1]).

How a turn goes

  1. The player types a guess, say 25, at turn 1.
  2. The script sends it as a row of CSV, 1,25, to POST /inputs/guess/rows. The input now lists turns 0 and 1.
  3. The script asks for hint[t = 1]. The service computes it, reading guess at turn 1, won_before at turn 1 and so won at turn 0, and answers higher.
  4. The script prints the answer and waits for the next guess, at turn 2.

Every query sees exactly the rows sent before it. It computes what it needs from those rows; with "options": {"pointCache": true} in a configuration, the service also keeps what earlier queries computed and reuses it while the rows it read are unchanged (shared caches).

A session in the terminal

Start the service in a first terminal, with no guesses yet (the file guess.csv holds only its header, t,value):

elucid8 serve program.el8 --http 127.0.0.1:8091

In a second terminal, send three guesses:

for row in 0,50 1,25 2,37; do
  printf '%s\n' "$row" | curl -s -o /dev/null -H 'Content-Type: text/csv' \
    --data-binary @- http://127.0.0.1:8091/inputs/guess/rows
done

and ask in elucid8 repl, about the last turn and about every turn so far:

elucid8/… at http://127.0.0.1:8091/: secret, won_before, won, hint, tries; input guess. Type help for commands, quit to leave.
elucid8> hint[t = last]
correct!
elucid8> hint[t = 0..last]
t = 0: lower
t = 1: higher
t = 2: correct!
elucid8> tries[t = last]
3
elucid8> won[t = 1]
false
elucid8> hint[t = 3]
already won: start a new game
elucid8> quit

hint[t = 3] has an answer although no guess was made at turn 3: the game was already won, so hint there does not read guess at all.

The play script

play.sh does the same in a loop: it starts the service on port 8091 (with guess.csv emptied), sends each guess you type as a row, prints hint at that turn, and stops when the guess is correct.

./play.sh
I am thinking of a number from 1 to 100.
Your guess: 50
  lower
Your guess: 25
  higher
Your guess: 37
  correct!
  You took 3 tries.

While it runs, elucid8 repl http://127.0.0.1:8091 in another terminal can ask about any turn of the game being played.

Tic-tac-toe, with the board in the Player

Two players take turns, X first. Each move is a row of the input move: the turn, and the square played, 1 to 9 from the top left. The board is a value over the turn and two more dimensions, x across and y up, as the eLucid8 Player draws a picture:

-- Tic-tac-toe. Each move is a row of the input "move":
-- t is the turn (0, 1, 2, ...), the value is the square played:
--   1 2 3
--   4 5 6
--   7 8 9
move = input("move", t : inf)

-- Moves played so far (a refused move does not count), and whose
-- turn it is: X (1) after an even number of moves, O (2) after an odd one.
played_before = 0 fby.t played
played = played_before + (if legal then 1 else 0)
player = if mod(played_before, 2) == 0 then 1 else 2

-- Cells are (x, y): x the column from the left, y the row from the
-- bottom, as the Player draws them. The square a cell is, 1 to 9.
square = restrict 3 * (2 - #y) + #x + 1 to (x : 3, y : 3) end

-- The board before this turn's move: empty at the start.
before = 0 fby.t board

-- Whether this turn's move can be played: the game is still on
-- and the square is empty.
legal = state_before == "playing"
        and (count 1 over (x : 3, y : 3) if square == move and before == 0 end) == 1

-- The board after each turn: 0 empty, 1 X, 2 O.
board = restrict
          if legal and square == move then player else before
        to (x : 3, y : 3) end

-- Whether player p has three in a line on the board.
fun wins(p) = rows or cols or diag or anti
  where
    rows = max (count 1 over (x : 3) if board == p end) over (y : 3) end == 3
    cols = max (count 1 over (y : 3) if board == p end) over (x : 3) end == 3
    diag = (count 1 over (x : 3) if board[y = #x] == p end) == 3
    anti = (count 1 over (x : 3) if board[y = 2 - #x] == p end) == 3
  end

-- The game after each turn.
state = if wins(1) then "X wins"
        else if wins(2) then "O wins"
        else if (count 1 over (x : 3, y : 3) if board == 0 end) == 0 then "draw"
        else "playing"

state_before = "playing" fby.t state

-- What the game says after each move.
says = if state_before != "playing" then "the game is over"
       else if not legal then "square taken, or not 1 to 9: play again"
       else state

-- The board as letters, for the Player: "X", "O", or "-" for empty.
mark = if board == 1 then "X" else if board == 2 then "O" else "-"
-- table move = t,value; 0,5; 1,1; 2,5; 3,9; 4,3; 5,7; 6,4; 7,6; 8,2
-- expect says[t = 0] = "playing"
-- expect says[t = 2] = "square taken, or not 1 to 9: play again"
-- expect player[t = 3] = 1
-- expect says[t = 8] = "O wins"
-- expect says[t = 9] = "the game is over"
-- expect mark[t = 8, x = 1, y = 2] = "O"
-- expect played[t = 8] = 8

Open in playground

What carries over is again fby: before is the board at the turn before, played_before the moves that counted, state_before whether the game was still on. A move to a square already taken is not legal, so the board stays as it was, the move does not count, and the same player plays again. wins is a function over the board; count … if … end counts the cells of a row, a column or a diagonal that hold the player's mark.

play.sh plays it in the terminal and, after the first move, opens mark, the board as letters, live in the Player (http://127.0.0.1:8092/player?value=mark&live): each move appears there as soon as it is sent. With elucid8 0.22.0, open the Player after the first move, as the script does: its live mode starts from the data there is. From 0.23.0 it waits for the first data by itself.

On the moves 5, 1, 5, 9, 3, 7, 4, 6, 2, X's second 5 is refused (the square is O's), and O completes the top row:

O to play:    O O O
   O X X
   X . X
  O wins

A player that cannot be beaten

In this game you are X and the program is O. O plays by minimax: it looks at every way the game can go on and chooses the move that is best for it whatever you play. In eLucid8 minimax is not a search the program carries out: it is a value over a dimension.

-- Tic-tac-toe against a player who cannot be beaten.
-- You are X and move first; the program is O.
-- Each of your moves is a row of the input "move": t is the turn
-- (0, 1, 2, ...), the value is the square you play:
--   1 2 3
--   4 5 6
--   7 8 9
move = input("move", t : inf)

-- A board is a number b in base 3: square k (0 to 8) is the k-th digit,
-- 0 empty, 1 X, 2 O. There are 3^9 = 19683 boards.
fun cell(k) = mod(div(#b, pow(3, k)), 3)

-- Who has three in a line on board b: 1 X, 2 O, 0 nobody.
fun line(p, q, r) = if cell(p) != 0 and cell(p) == cell(q) and cell(q) == cell(r)
                    then cell(p) else 0
winner = restrict
           max(max(max(line(0, 1, 2), line(3, 4, 5)), max(line(6, 7, 8), line(0, 3, 6))),
               max(max(line(1, 4, 7), line(2, 5, 8)), max(line(0, 4, 8), line(2, 4, 6))))
         to (b : 19683) end

-- Squares filled, and how many are O's.
filled = restrict count 1 over (i : 9) if cell(#i) != 0 end to (b : 19683) end
noughts = restrict count 1 over (i : 9) if cell(#i) == 2 end to (b : 19683) end

-- Minimax: how good board b is for O, playing on perfectly from it.
-- A win is worth more the sooner it comes; a loss less the later.
-- X is to move when X and O have played as often: filled == 2 * noughts.
value = restrict
          if winner == 2 then 10 - filled
          else if winner == 1 then filled - 10
          else if filled == 9 then 0
          else if filled == 2 * noughts
            then min value[b = #b + pow(3, #i)] over (i : 9) if cell(#i) == 0 end
            else max value[b = #b + 2 * pow(3, #i)] over (i : 9) if cell(#i) == 0 end
        to (b : 19683) end

-- O's best square on board b (0 to 8): the first best one.
reply = restrict
          argmax.i value[b = #b + 2 * pow(3, #i)] over (i : 9) if cell(#i) == 0 end
        to (b : 19683) end

-- The game, turn by turn. The board before your move:
before = 0 fby.t board

-- Your move is played if the game is on and the square is empty.
legal = state_before == "playing" and move >= 1 and move <= 9
        and mod(div(before, pow(3, move - 1)), 3) == 0
after_you = if legal then before + pow(3, move - 1) else before
finished = winner[b = after_you] != 0 or filled[b = after_you] == 9

-- Then O replies, unless your move ended the game.
answer = if legal and not finished then reply[b = after_you] + 1 else eod
board = if not legal or finished then after_you
        else after_you + 2 * pow(3, answer - 1)

-- The game after each turn.
state = if winner[b = board] == 2 then "I win"
        else if winner[b = board] == 1 then "you win"
        else if filled[b = board] == 9 then "draw"
        else "playing"
state_before = "playing" fby.t state

-- What the program says after each of your moves.
says = if state_before != "playing" then "the game is over"
       else if not legal then "square taken, or not 1 to 9: play again"
       else state

-- The board as letters, for the Player: x across, y up, as drawn.
mark = restrict
         if mod(div(board, pow(3, 3 * (2 - #y) + #x)), 3) == 1 then "X"
         else if mod(div(board, pow(3, 3 * (2 - #y) + #x)), 3) == 2 then "O"
         else "-"
       to (x : 3, y : 3) end
-- table move = t,value; 0,5; 1,9; 2,4
-- expect value[b = 0] = 0
-- expect answer[t = 0] = 1
-- expect answer[t = 1] = 3
-- expect answer[t = 2] = 2
-- expect says[t = 2] = "I win"
-- expect board[t = 0] = 83
-- expect mark[t = 2, x = 1, y = 2] = "O"

Open in playground

b is a board, written as a number in base 3: square k is the k-th digit, so 0 is the empty board and the 19,683 numbers below 3^9 are every way of filling the squares. value is how good board b is for O: a won or drawn board is scored directly, and any other board is worth the smallest of its children when X is to move (X does what is worst for O), and the largest when O is to move. Its children are boards with one more mark, value[b = #b + pow(3, #i)]: so value is defined over boards, by its value at other boards. reply is the square whose board is best for O, the first of the best (argmax.i).

The game itself is the turn-by-turn part below it: your move, then answer, O's reply at the board after your move.

Nothing is searched until something asks. A query for answer[t = 0] demands reply at the board after your first move, which demands value at each board O could make, which demands value at the boards after those, and so on to the end of every game. Each board's value is computed once and then reused, so the whole tree from the empty board, value[b = 0], is about 5,500 boards of the 19,683, each computed once: about 0.06 s with the elucid8 command (measured on an Apple M5 Max). Boards no game can reach (nine X's, say) are never computed.

every-game.py plays every game X can play against it, through one service: each game so far is sent as a whole file of moves (an advance of the input move), and the service is asked what O plays and how the game stands. O never loses:

python3 every-game.py
569 games: O won 386, drew 183, lost 0 (…)

A shop counter

A shop's stock, kept up to date as sales and deliveries arrive. Each event is a row of the input change: the event's number t, the item, and how much (negative for a sale):

-- A small shop's stock, kept up to date as sales and deliveries come in.
-- Each event is a row of the input "change": t counts the events
-- (0, 1, 2, ...), item names what changed, and the value is how much:
-- negative for a sale, positive for a delivery.
change = input("change", t : inf, item : {"coffee", "tea", "milk", "sugar"})

-- Stock at opening, and the level at which to reorder.
opening = if #item == "coffee" then 40
          else if #item == "tea" then 30
          else if #item == "milk" then 24
          else 20
reorder_at = if #item == "milk" then 8 else 10

-- This event's change to an item: 0 for the items it does not name
-- (no row for them: missing data), and 0 after the last event (eod).
delta = default(default(change, 0), 0, "missing")

-- Stock before and after each event. A sale of more than is in stock
-- is refused, and the stock stays as it was.
before = opening fby.t stock
refused = before + delta < 0
stock = if refused then before else before + delta

-- Sold so far, per item.
sold = (0 fby.t sold) + (if delta < 0 and not refused then -delta else 0)

-- What the shop should hear about each item after each event.
status = if refused then "refused: not enough in stock"
         else if stock == 0 then "out of stock"
         else if stock < reorder_at then "reorder now"
         else "ok"

-- How many items need attention, and the best seller so far.
attention = count 1 over (item : {"coffee", "tea", "milk", "sugar"})
              if stock < reorder_at end
best_seller = argmax.item sold over (item : {"coffee", "tea", "milk", "sugar"}) end
-- table change = t,item,value; 0,coffee,-3; 1,sugar,-15; 2,sugar,-8; 3,sugar,20
-- expect stock[t = 0, item = "coffee"] = 37
-- expect status[t = 1, item = "sugar"] = "reorder now"
-- expect refused[t = 2, item = "sugar"] = true
-- expect stock[t = 2, item = "sugar"] = 5
-- expect stock[t = 3, item = "sugar"] = 25
-- expect sold[t = 3, item = "sugar"] = 15
-- expect attention[t = 1] = 1
-- expect best_seller[t = 3] = "sugar"

Open in playground

The items are a dimension of texts, item, listed in the input. A row names one item, so at any other item the input has no row at that turn, which is missing data (an error of kind missing): default(default(change, 0), 0, "missing") reads that as no change, and so are the turns after the last event, where it is eod (the inner default fills eod, the outer one missing data). A sale of more than is in stock is refused, and the stock stays as it was: whether it is refused depends on the stock before, which is fby. attention counts the items below their reorder level, and best_seller is the item sold most so far, by argmax.item.

shop.py is the counter: you type sell coffee 3, deliver milk 24 or stock, and it sends each sale or delivery as a row (POST /inputs/change/rows) and asks stock, status, sold and best_seller:

Type: sell coffee 3 | deliver milk 24 | stock | quit
> sell coffee 3
   coffee: 37 in stock (ok)
   stock, live in the Player: http://127.0.0.1:8097/player?value=stock&live
> sell sugar 15
   sugar: 5 in stock (reorder now)
> sell sugar 8
   sugar: 5 in stock (refused: not enough in stock)
> deliver sugar 20
   sugar: 25 in stock (ok)
> stock
   item     stock  sold  status
   coffee      37     3  ok
   tea         30     0  ok
   milk        24     0  ok
   sugar       25    15  ok
   best seller so far: sugar
> quit

A day's sales, replayed. The same program runs with no one typing: replay.json gives the input the rows of sales-day.csv, a day's twenty events, one a second (inputs given rows over time):

{
  "format": "elucid8-deploy/2",
  "inputs": {
    "change": { "from": { "builtin": "replay", "file": "sales-day.csv", "every": "1s" } }
  }
}
elucid8 serve program.el8 --config replay.json --http 127.0.0.1:8097

Watch it with elucid8 repl http://127.0.0.1:8097 (watch stock[t = last, item = "coffee"]) or in the Player (http://127.0.0.1:8097/player?value=stock&live). After the last event coffee is at 26 and has sold the most: 44.

Sales another program writes to a file. A till that appends each sale to a file needs no script either: follow.json gives the input the rows another program appends to live.csv, as they are written. The service looks at the file every 250 ms and takes each complete line added to it as a row (inputs given rows over time). It needs the elucid8 command from 0.23.0 (0.22.0 does not have it).

{
  "format": "elucid8-deploy/2",
  "inputs": {
    "change": { "from": { "builtin": "follow", "file": "live.csv" } }
  }
}
printf 't,item,value\n' > live.csv
elucid8 serve program.el8 --config follow.json --http 127.0.0.1:8097

Each event appended to live.csv (printf '0,coffee,-5\n' >> live.csv) is then a row of change, and the answers follow it.

The program does not change between the three: typed at a counter, replayed from a file or followed as another program writes it, a sale is a row of change.

What carries over

The same programs can open a window of their own: Programs in a window.