How do you return from a function early in Clojure?

后端 未结 8 1257
不知归路
不知归路 2020-12-08 13:48

Common Lisp has return-from; is there any sort of return in Clojure for when you want to return early from a function?

相关标签:
8条回答
  • 2020-12-08 14:03

    There isn't any explicit return statement in clojure. You could hack something together using a catch/throw combination if you want to, but since clojure is much more functional than common lisp, the chances you actually need an early return right in the middle of some nested block is much smaller than in CL. The only 'good' reason I can see for return statements is when you're dealing with mutable objects in a way that's not idiomatic in clojure.

    I wouldn't go as far as saying that it's never useful, but I think in Clojure, if your algorithm needs a return statement, it's a major code smell.

    0 讨论(0)
  • Unless you're writing some really funky code, the only reason you'd ever want to return early is if some condition is met. But since functions always return the result of the last form evaluated, if is already this function — just put the value that you want to return in the body of the if and it will return that value if the condition is met.

    0 讨论(0)
  • 2020-12-08 14:06

    I'm no expert in Clojure, but it seems it does not have those construct to try to be more functional. Take a look at what Stuart Halloway says here:

    Common Lisp also supports a return-from macro to "return" from the middle of a function. This encourages an imperative style of programming, which Clojure discourages.

    However, you can solve the same problems in a different way. Here is the return-from example, rewritten in a functional style so that no return-from is needed:

    (defn pair-with-product-greater-than [n]
     (take 1 (for [i (range 10) j (range 10) :when (> (* i j) n)] [i j])))
    

    That is, use lazy sequences and returning values based on conditions.

    0 讨论(0)
  • 2020-12-08 14:06

    The if option already given is probably the best choice, and note since maps are easy, you can always return {:error "blah"} in the error condition, and{result: x} in the valid condition.

    0 讨论(0)
  • 2020-12-08 14:10

    In short, no. If this is a real problem for you then you can get around it with "the maybe monad" Monads have a high intellectual overhead so for many cases clojurians tend to avoid the "if failed return" style of programming.

    It helps to break the function up into smaller functions to reduce the friction from this.

    0 讨论(0)
  • 2020-12-08 14:12

    There isn't a return statement in Clojure. Even if you choose not to execute some code using a flow construct such as if or when, the function will always return something, in these cases nil. The only way out is to throw an exception, but even then it will either bubble all the way up and kill your thread, or be caught by a function - which will return a value.

    0 讨论(0)
提交回复
热议问题