Reputation: 5
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?
Upvotes: 0
Views: 209
Reputation: 9865
Apply the lesson you learned from do_stuff
on -main
:
(defn -main
([] (do_stuff))
([& args] (do_stuff (apply str args))))
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)))
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))
Upvotes: 1