commit 5b17b7ea8ef7ba98d9a452e12dc461c5fa1b0b11
parent e0f2a2ec14bd86f158061c82b76ccfa30b7455f0
Author: glenda <glenda@device>
Date: Tue, 25 Oct 2022 22:12:20 +0000
add src/list
Diffstat:
3 files changed, 68 insertions(+), 0 deletions(-)
diff --git a/src/list/list.c b/src/list/list.c
@@ -0,0 +1,61 @@
+#include <u.h>
+#include <libc.h>
+
+#include "list.h"
+
+enum {
+ CNull = 0,
+ CPair,
+ CAtom,
+ CError = -1,
+};
+
+typedef struct Cell Cell;
+struct Cell {
+ char type;
+ void *p;
+};
+
+typedef struct Pair Pair;
+struct Pair {
+ union {
+ Cell p[2];
+ struct {
+ Cell fst;
+ Cell snd;
+ };
+ };
+};
+
+Cell
+cons(Cell fst, Cell snd)
+{
+ if ((snd.type != CPair) && (snd.type != CNull)) snd = cons(snd, (Cell){CNull, 0});
+ Pair *p = malloc(sizeof(Pair));
+ p->fst = fst;
+ p->snd = snd;
+ return (Cell){CPair, p};
+}
+
+Cell
+head(Cell c)
+{
+ return (c.type == CPair) ? ((Pair *)c.p)->fst : (Cell){CError, "not a pair"};
+}
+
+Cell
+tail(Cell c)
+{
+ return (c.type == CPair) ? ((Pair *)c.p)->snd : (Cell){CError, "not a pair"};
+}
+
+void
+main(void)
+{
+ char *a = "hello", *b = "world";
+ Cell A = {CAtom, a}, B = {CAtom, b};
+ Cell C = cons(A, B);
+ Cell r = head(tail(C));
+ char *s = r.p;
+ print("%s\n", s);
+}
diff --git a/src/list/list.h b/src/list/list.h
diff --git a/src/list/mkfile b/src/list/mkfile
@@ -0,0 +1,7 @@
+</$objtype/mkfile
+
+TARG=list
+OFILES=list.$O
+HFILES=list.h
+
+</sys/src/cmd/mkone