Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure functions - returning value computed before the last statement

I have some tests written in clojure. This is a simple example:

(defn test1
  []
  (start-server)
  (run-pvt-and-expect "PVT-0")
  (stop-server)
 )

I would like to return the result of "run-pvt-and-expect", but I need to execute other functions after it. How can I do this in clojure in a functional way (without using constructs like "let")? Thanks.

Note: I read this question and its answers but couldn't apply it to my case. Also, a comment asked for examples that were never given, so please consider this as an example...

like image 549
sebi Avatar asked Dec 04 '22 10:12

sebi


1 Answers

You can do this using a finally block.

(try 
    (+ 2 3)
    (finally (+ 6 7)))

produces a result of 5 not 13.

Here is the relevant doc page. The releavant part is:

any finally exprs will be evaluated for their side effects.

Another option would be to write a macro like with-open to start and stop your server while returning the right results. Though that just moves the problem to how do you write the macro, since it would either need to use a let or the try finally construct above.

like image 157
stonemetal Avatar answered Jan 19 '23 00:01

stonemetal