functional programming - if-else branching in clojure -


i'm teaching myself clojure.

in non-fp language, enough write nested if's, , if didn't put else, control flow out of if block. example:

thing myfunc() {   if(cond1)   {     if(cond2)       return something;   }   return somethingelse; } 

however, in clojure, there's no return statement (that know of), if write:

(defn myfunc []   (if (cond1)       (if (cond2) something))   somethingelse) 

then there's no "return" on "something". seems kind of say, ok, here have value, let's keep on executing. obvious solution combine conditions, i.e.:

(if (and (cond1) (cond2))         somethingelse) 

but gets unwieldy/ugly large conditions. also, take additional finagling add statement "else" part of cond1. there kind of elegant solution this?

this subtle difference between imperative , functional approach. imperative, can place return in place of function, while functional best way have clear , explicit exeecution paths. people (me including) prefer latter approach in imperative programming well, recognizing more obvious , manageable , less error-prone.

to make function explicit:

thing myfunc() {   if(cond1) {     if(cond2)       return something;   }    return somethingelse; } 

you can refactor to:

thing myfunc() {   if(cond1 && cond2) {       return something;   } else {     return somethingelse;   } } 

in clojure, equivalent is:

(defn myfunc []   (if (and cond1 cond2)              somethingelse)) 

if need "else", java version become:

thing myfunc() {   if(cond1) {     if(cond2) {       return something;     } else {       return newelse;     }   } else {     return somethingelse;   } } 

... , clojure equivalent:

(defn myfunc []   (if cond1       (if cond2 newelse)       somethingelse)) 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -