Search code examples
clojure

How to append strings to a vector in Clojure


I'm new in Clojure and function programming in general.

I want to execute a set of if/else's and if the condition is true I want to append some string at the of a list.

In JavaScript would be like this:

const a = 1;
const b = 2;
const c = 1;

const errors = [];

if (a !== b) {
  errors.push("A and B should not be different");
}

if (a == c) {
  errors.push("A and C should not be equal");
}

console.log(errors);

How could I accomplish this with Clojure?


Solution

  • cond-> is good for conditionally modifying some value, and threading those operations together:

    (def a 1)
    (def b 2)
    (def c 1)
    
    (cond-> []
      (not= a b) (conj "A and B should not be different")
      (= a c) (conj "A and C should not be equal"))
    

    The first argument to cond-> is the value to be threaded through the righthand-side forms; it's the empty vector here. If none of the LHS conditions are met, it will return that empty vector. For each condition that's met, it'll thread the vector value into the RHS form, which is conj here for adding things to the vector.

    Check out the -> and ->> macros for other threading examples.