Fix mapO behavior to match typical lambdas.

Fix isCd REPL check.
Add tic-tac-toe.pbl
This commit is contained in:
Sage Vaillancourt 2022-05-02 16:55:17 -04:00 committed by Sage Vaillancourt
parent 139e912548
commit b03d4cbd3f
5 changed files with 80 additions and 4 deletions

View File

@ -9,7 +9,8 @@
; Otherwise invoke
)))
(def first-where (fn (list condition) (
(def first-where (fn (list condition)
"Get the first element from the given list that matches the given condition. Halts on first error." (
(def next (first list))
(if (iserr next) ()
(if (condition next) next (first-where (rest list) condition))

69
src/examples/tic-tac-toe.pbl Executable file
View File

@ -0,0 +1,69 @@
#!/usr/bin/pl
(def empty-board (
" " " " " "
" " " " " "
" " " " " "
))
(def print-board (fn (board) (
(sys "clear")
(def '(a b c
d e f
g h i) board)
(prnl (cat " " a " | " b " | " c))
(prnl "-----------")
(prnl (cat " " d " | " e " | " f))
(prnl "-----------")
(prnl (cat " " g " | " h " | " i))
)))
(def do-move (fn (board player) (
(def input (inp))
(def spot (eval input))
(def i 0)
(map (fn (piece) (
(set i (+ 1 i))
(if (= i spot) player piece)
)) board)
)))
(def winning-row (fn (row) (
(def '(a b c) row)
(& (not (= " " a)) (= a b c))
)))
(def get-winner (fn (board) (
(sys "clear")
(def '(a b c
d e f
g h i) board)
(if (winning-row (a b c)) a
(if (winning-row (d e f)) d
(if (winning-row (g h i)) g
(if (winning-row (a d g)) a
(if (winning-row (b e h)) b
(if (winning-row (c f i)) c
(if (winning-row (a e i)) a
(if (winning-row (c e g)) c
" "
))))))))
)))
(def next-player (fn (current) (
(if (= current "X") "O" "X")
)))
(def game (fn (board player) (
(if (= " " (get-winner board)) (
(print-board board)
(def b (do-move board player))
(game b (next-player player))
) (
(print-board board)
(prnl "")
(prnl "Game over! " (next-player player) " wins!")
))
)))
(game empty-board "X")

View File

@ -102,7 +102,7 @@ void repl(struct Environment* env)
}
add_history(buf);
int isCd = strncmp("cd ", buf, 3);
int isCd = strncmp("cd ", buf, 3) == 0;
int isHelp = buf[0] == '?' && (buf[1] == ' ' || buf[1] == '\0');
if (isCd || isHelp) {
char* oldBuf = buf;

View File

@ -183,7 +183,7 @@ struct StructDef {
struct StructObject {
int definition;
struct Object* fields; // Order should match that in the definition.
Object* fields; // Order should match that in the definition.
};
#define lambdaDocs(LAMBDA_OBJECT) (LAMBDA_OBJECT)->lambda->params.docStrings

View File

@ -147,7 +147,13 @@ Object mapO(Object* params, int length, struct Environment* env)
struct Environment newEnv = envForLambda(lambdaParams, &tempInput, listLength(lambdaParams), env);
// Add the lambda evaluation to the list
addToList(outputList, eval(&lambda.lambda->body, &newEnv));
Object ret = eval(&lambda.lambda->body, &newEnv);
if (isListy(ret)) {
Object o = cloneObject(*tail(&ret));
cleanObject(&ret);
ret = o;
}
addToList(outputList, ret);
deleteEnv(&newEnv);
cleanObject(&tempInput);
}