Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run two commands in a row after an if statement in Clojure

Tags:

clojure

Why does the following Clojure program throw a NullPointerException?

user=> (defn x []  
       "Do two things if the expression is true."
       (if true ((println "first expr") (println "second expr")) false))

user=> (x)
first expr
java.lang.NullPointerException (NO_SOURCE_FILE:0)
second expr

This is a simplified version of my actual use case, where I want to execute maybe three statements (pull values from the DB) before returning a map - {:status 200, :body "Hello World"} inside of the branch.

like image 763
Kevin Burke Avatar asked Sep 26 '11 01:09

Kevin Burke


2 Answers

It is trying to treat the result of the first println as a function to call on the second println function.

You need a do.

(defn x []  
   "Do two things if the expression is true."
   (if true (do (println "first expr") (println "second expr")) false))

(x)

The do special form (progn in CL, begin in Scheme) executes each of its arguments in sequence and returns the result of the last one.

like image 63
Random832 Avatar answered Nov 11 '22 16:11

Random832


If nil is ok as a return value in the else case, consider using when which has an implicit do block:

(defn x []  
  "Do two things if the expression is true."
  (when true
    (println "first expr") 
    (println "second expr")))
like image 25
Dave Ray Avatar answered Nov 11 '22 16:11

Dave Ray