Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a default value if current value is nil in Clojure?

Tags:

clojure

I'm coming from a heavy javascript background and learning clojure.

In js we can do;

var aVariable; //evaluates as falsy
var x = aVariable || 'my Default String';

How do you do this in clojure?

Currently I'm reading a header out of a request map coming from compojure.

(let [x-forwarded-for (get-in request [:headers "x-forwarded-for"])]
    (println x-forwarded-for)
)

In the case where the 'x-forwarded-for' header doesn't exist, the x-forwarded-for value is nil. What's the proper way to test for nil and then reassign x-forwarded-for to another value?

like image 859
Geuis Avatar asked Sep 05 '13 18:09

Geuis


2 Answers

You can use the built-in or:

(let [x-forwarded-for (or (get-in request [:headers "x-forwarded-for"]) "my Default String")]
  (println x-forwarded-for))

If the first clause is nil, it will use the second.

like image 152
prismofeverything Avatar answered Sep 29 '22 13:09

prismofeverything


Luckily the get-in function has a not-found parameter for exactly this use case:

(let [x-forwarded-for (get-in request [:headers "x-forwarded-for"]
                              "default value")]
    (println x-forwarded-for))

In general, you could use or as @prismofeverything said.

like image 25
bdesham Avatar answered Sep 29 '22 15:09

bdesham