Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-> operator that breaks evaluation on encountering a nil/false return

Tags:

clojure

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 ?

like image 364
murtaza52 Avatar asked Sep 17 '12 04:09

murtaza52


People also ask

Which operator returns true or false?

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.

What does the || operator do?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.

What does the && operator do in JavaScript?

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 .

What is ?: operator in TypeScript?

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]


2 Answers

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.

like image 74
Alexey Kachayev Avatar answered Nov 13 '22 03:11

Alexey Kachayev


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.

like image 44
Rafał Dowgird Avatar answered Nov 13 '22 04:11

Rafał Dowgird