about summary refs log tree commit diff
path: root/fun/wcl
diff options
context:
space:
mode:
Diffstat (limited to 'fun/wcl')
-rw-r--r--fun/wcl/default.nix14
-rw-r--r--fun/wcl/wc.lisp34
2 files changed, 48 insertions, 0 deletions
diff --git a/fun/wcl/default.nix b/fun/wcl/default.nix
new file mode 100644
index 000000000000..e4d9804c807c
--- /dev/null
+++ b/fun/wcl/default.nix
@@ -0,0 +1,14 @@
+{ depot, ... }:
+
+depot.nix.buildLisp.program {
+  name = "wc";
+
+  srcs = [
+    ./wc.lisp
+  ];
+
+  deps = with depot.third_party.lisp; [
+    unix-opts
+    iterate
+  ];
+}
diff --git a/fun/wcl/wc.lisp b/fun/wcl/wc.lisp
new file mode 100644
index 000000000000..83c7e8c4f1cc
--- /dev/null
+++ b/fun/wcl/wc.lisp
@@ -0,0 +1,34 @@
+(defpackage wc
+  (:use #:cl #:iterate)
+  (:export :main))
+(in-package :wc)
+(declaim (optimize (speed 3) (safety 0)))
+
+(defun main ()
+  (let ((filename (cadr (opts:argv)))
+        (space (char-code #\Space))
+        (newline (char-code #\Newline)))
+    (with-open-file (file-stream filename :element-type '(unsigned-byte 8))
+      (iter
+        (for byte in-stream file-stream using #'read-byte)
+        (for previous-byte previous byte)
+        (for is-newline = (eql newline byte))
+
+        ;; Count each byte
+        (sum 1 into bytes)
+
+        ;; Count every newline
+        (counting is-newline into newlines)
+
+        ;; Count every "word", unless the preceding character already
+        ;; was a space or we are at the beginning of the file.
+        (when (or (eql space previous-byte)
+                  (eql newline previous-byte)
+                  (not previous-byte))
+          (next-iteration))
+
+        (counting (or is-newline (eql space byte))
+                  into words)
+
+        (declare (fixnum bytes newlines words))
+        (finally (format t "  ~A ~A ~A ~A~%" newlines words bytes filename))))))