4 ms·
Clojure has some conditional threading macros like `some->` and `cond->` that are useful for transforming data conditionally. `cond->` takes pairs of tests and
by pgt 9y ago
Clojure has some conditional threading macros like `some->` and `cond->` that are useful for transforming data conditionally.
`cond->` takes pairs of tests and forms where a form is threaded through the subsequent forms if the test expression is true.
Example from documentation (https://clojuredocs.org/clojure.core/cond-%3E https://clojuredocs.org/clojure.core/cond-%3E):
(cond-> 1 ; we start with 1
true inc ; the condition is true so (inc 1) => 2
false (* 42) ; the condition is false so the operation is skipped
(= 2 2) (* 3)) ; (= 2 2) is true so (* 2 3) => 6
;;=> 6
;; notice that the threaded value gets used in
;; only the form and not the test part of the clause.
- justinhj 9y agoThis is conceptually different to a Monad in Haskell. Monad bind operations have short circuit failure, so in the example above all of the operations would have to succeed or none of them would. cond-> looks like a useful function but you have to hold the state in your head at each point to debug it. What happens if two steps change the type from int to string then the follow step requires the string, but if the previous step fails you would get an int? Seems it would be very prone to runtime surprises
- networked 9y agocond-> doesn't, but some-> short circuits on nil. Similarly, with expressions in Elixir short circuit on a failed pattern match. https://clojuredocs.org/clojure.core/some-%3E https://clojuredocs.org/clojure.core/some-%3E https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1 https://hexdocs.pm/elixir/Kernel.SpecialForms.html#with/1