I want to thread an input through a series of functions, just what the -> operator does. However if any of the functions returns nil / false then I would like to break the evaluation and return back an error message. How do I do that, is there some operator / macro that provides this functionality ?
The true operator returns the bool value true to indicate that its operand is definitely true. The false operator returns the bool value true to indicate that its operand is definitely false.
The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.
The logical AND ( && ) operator (logical conjunction) for a set of boolean operands will be true if and only if all the operands are true . Otherwise it will be false .
Ternary operator The ternary operator is one of the most popular shorthands in JavaScript and TypeScript. It replaces the traditional if… else statement. Its syntax is as follows: [condition] ? [ true result] : [false result]
Try this one: -?>
From documentation:
(-?> "foo" .toUpperCase (.substring 1)) returns "OO"
(-?> nil .toUpperCase (.substring 1)) returns nil
If you will use ->
macro for second example, you will definitely get NullPointerException
.
There is also the maybe-m
monad in clojure.algo.monads
. Being part of the monads framework it is more heavyweight than the -?>
macro, so it makes sense to use maybe-m
if you are using monads anyway or if your computation graph is more complicated than a simple chain of functions.
Unlike the threading macros, thedomonad
composition can handle multiple argument functions that take arguments from multiple previous steps of computation:
(domonad maybe-m
[a 1
b nil
c (* a b)]
c)
In this example,(* a b)
won't get evaluated, since b
is nil. The whole expression will return nil instead of throwin an exception from trying to multiply by nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With