Home > front end >  Clojure: using an If statement as a parameter in a function call, if there are no args, pass nothing
Clojure: using an If statement as a parameter in a function call, if there are no args, pass nothing

Time:05-29

So I have a function do_stuff that can take 0 or 1 arguments as follows

(defn do_stuff 
   ([]
    (println "no arguments here"))
   ([arg]
    (println "here's the argument"))

(defn -main
  [& args]
  (do_stuff (if args (apply str args))

How do I return no argument from the if statement, so that I can print the "no arguments here" string? Edit: Using the when instead of if returns nil, which is still an argument?

CodePudding user response:

Using multi-arity definitions

Apply the lesson you learned from do_stuff on -main:

(defn -main
  ([] (do_stuff))
  ([& args] (do_stuff (apply str args))))

Externalizing condition using if (or cond)

An if expression without else branch still returns nil but returning nil is not returning nothing. That is you can't make it with an if or when expression that it just returns nothing. At least not in functional languages like Clojure is.

You could alternatively externalize your if like this:

(defn -main
  [& args]
  (if args 
     (do_stuff (apply str args))
     (do_stuff)))

Using apply

@EugenePakhomov's idea:

(defn -main
  [& args]
  (apply do_stuff (if args [(apply str args)] [])))

But what I think is: How about to put the (apply str args) part inside do_stuff?

(defn do_stuff 
   ([]
    (println "no arguments here"))
   ([& args]
    (let [arg (apply str args)]
      (println "here's the argument"))))

Because then you could very elegantly do:

(defn -main [& args]
  (apply do_stuff args))
  • Related