The result of the last expression evaluated is always returned. Hence, the shape of the function is what determines the points of return and the returned values. For example, if you're entire function is defined as one (if ...) statement, there are two possible points of return, each of the branches.
But I think you're probably asking if you can return early from a function, like in Java or Javascript. No, there's no return "statement" in Clojure. You just have to structure your functions a certain way. Here's an alternate version of your pyramid function which uses (recur ...). This is equivalent to calling pyramid recursively, but the compiler is able to optimize this recursive call away. In other words, it will never overflow the stack. (defn pyramid [n] (when (pos? n) (dotimes [_ n] (print "* ")) (println) (recur (dec n)))) On Thursday, April 14, 2016 at 9:23:58 PM UTC-4, Varun Kamra wrote: > > On Thursday, April 14, 2016 at 5:58:33 PM UTC-7, Varun Kamra wrote: > > Hey guys I am new to clojure. I was just experimenting by printing a > pyramid of stars 5 rows and 5 column. Here's the code: > > > > (defn pyramid [j i] > > (if (and (= i 0) (neg? > > (println "There's your pyramid")) > > (if (= j 0) > > (do (println) > > (pyramid (- i 1) (- i 1))) > > (do (print "* ") > > (pyramid (- j 1) i)))) > > > > It's working fine till it prints the pyramid, but after printing it, it > continues printing a lot of stars and eventually fail with stack overflow. > I am guessing that a if I put a negative check I can prevent it but I > wanted to know if there's a way to return from the recursive call instead. > > I understood now, it was going in the else condition of the if so here'so > the modified code > > (defn pyramid [j i] > (if (= i 0) > (println "There's your pyramid")) > (if (= j 0) > (do (println) > (pyramid (- i 1) (- i 1)))) > (if (not (neg? j)) > (do (print "* ") > (pyramid (- j 1) i)))) > > But my question still stands if ther's a way to return from function. > > -- You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups "Clojure" group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.