From 2ab93de543f36b0c93cbc692814ee88d671e9fa7 Mon Sep 17 00:00:00 2001 From: Nasado Date: Wed, 21 Aug 2024 20:11:25 -0600 Subject: [PATCH 1/2] Add functional versions of threading macros --- CHANGELOG.md | 1 + src/boot/boot.janet | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1f6833eb..6d373696c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to this project will be documented in this file. These streams cannot be directly read to and written from, but can be passed to subprocesses. - Add `array/join` - Add `tuple/join` +- Add `fn->` and `fn-?>` ## 1.35.2 - 2024-06-16 - Add `bundle/add-bin` to make installing scripts easier. This also establishes a packaging convention for it. diff --git a/src/boot/boot.janet b/src/boot/boot.janet index ba6774ca4..a940fb2ed 100644 --- a/src/boot/boot.janet +++ b/src/boot/boot.janet @@ -1371,6 +1371,15 @@ (keep-syntax! n parts)) (reduce fop x forms)) +(defn fn-> + ``Threading function. Calls the first of the functions it's given with x as + the only argument, then calls the second of the functions with the result, + and so on. Useful for expressing pipelines of data.`` + [x & funs] + (var x x) + (each fun funs (set x (fun x))) + x) + (defmacro -?> ``Short circuit threading macro. Inserts x as the second value in the first form in `forms`, and inserts the modified first form into the second form @@ -1403,6 +1412,19 @@ ~(let [,sym ,last] (if ,sym ,(keep-syntax! n parts)))) (reduce fop x forms)) +(defn fn-?> + ``Short circuit threading function. Calls the first of the functions it's + given with x as the only argument, then calls the second of the functions + with the result, and so on. The pipeline will return nil if an intermediate + value is nil. Useful for expressing pipelines of data.`` + [x & funs] + (var x x) + (prompt :fn-?> + (each fun funs + (set x (fun x)) + (when (nil? x) (return :fn-?> nil))) + x)) + (defn- walk-ind [f form] (def ret @[]) (each x form (array/push ret (f x))) From 5a689d81847016157ed945eeee369c0821c23c1f Mon Sep 17 00:00:00 2001 From: Nasado Date: Thu, 22 Aug 2024 18:19:06 -0600 Subject: [PATCH 2/2] Implement fn-?> with a while loop --- src/boot/boot.janet | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/boot/boot.janet b/src/boot/boot.janet index a940fb2ed..3e35c51e7 100644 --- a/src/boot/boot.janet +++ b/src/boot/boot.janet @@ -1419,11 +1419,12 @@ value is nil. Useful for expressing pipelines of data.`` [x & funs] (var x x) - (prompt :fn-?> - (each fun funs - (set x (fun x)) - (when (nil? x) (return :fn-?> nil))) - x)) + (var index 0) + (def len (length funs)) + (while (not (or (>= index len) (nil? x))) + (set x ((in funs index) x)) + (++ index)) + x) (defn- walk-ind [f form] (def ret @[])