From d9b018909b270fc39752d6b541bde0e5df6e33e5 Mon Sep 17 00:00:00 2001 From: Scott Olsen Date: Wed, 23 Mar 2022 20:32:31 -0400 Subject: [PATCH] feat: add maybe and result thread macros These macros each thread the value of a Maybe or Result through subsequent forms only when the Maybe or Result is a Just/Success value, returning Nothing/Error otherwise. It's a convenient way to execute some sequence of forms when a Maybe/Result returning function is successful, immediately returning the error value otherwise. --- core/ControlMacros.carp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/core/ControlMacros.carp b/core/ControlMacros.carp index e13142aa3..e764c3eb5 100644 --- a/core/ControlMacros.carp +++ b/core/ControlMacros.carp @@ -46,6 +46,26 @@ Example: (defmacro -> [:rest forms] (thread-first-internal forms)) +(doc ?-> + ("threads the value contained in a maybe through the following " false) + "forms iff, the Maybe is a Just." + "" + "Returns Nothing if the Maybe is Maybe.Nothing.") +(defmacro ?-> [maybe :rest forms] + (list 'match maybe + (list 'Maybe.Just 'v) (list 'Maybe.Just (thread-first-internal (cons 'v forms))) + '_ (list 'Maybe.Nothing))) + +(doc /-> + ("threads the value contained in a Result through the following" false) + "forms iff, the Result is a Success" + "" + "Returns the erorr if the Result is Result.Error.") +(defmacro /-> [result :rest forms] + (list 'match result + (list 'Result.Success 'v) (list 'Result.Success (thread-first-internal (cons 'v forms))) + 'y 'y)) + (doc --> "threads the first form through the following ones, making it the last argument.