Program flow - failure if one calculation is not performed

Sorry if this question makes no sense.

I am currently writing a small application, and I want to “combine” some functions together that form a wider calculation.

So, for example, I have a function that calls a web service and returns hash-mapas a result, or nilif it was an error or something went wrong. The next function in the chain takes a map and performs some additional processing, and then passes it to the next function ... and so on.

The fact is that if the first function fails, it moves on to the next function nil, and it will throw a null pointer (or something else), and I do not want it to even get to this stage. So, in other words, I want all the calculations to fail if one element in the chain fails.

eg.

;successful computation = function1 returns W -> function2 returns X -> function3 returns Y -> function4 returns Z -> Z
;failed computation = function1 returns W -> function2 returns X -> function3 returns nil -> nil
(-> (function1 "http://webservice.com") (function2) (function3) (function4))

The fact is that I don’t want each of my functions to reset each of my functions if(nil? arg), ideally I would like an abstraction that could take care of this for me, but I’m actually not very accessible in Clojure

I was thinking about using a Scala style type Option, which could be Some(value)or None, but I still have to put my code with these checks at the beginning

Any ideas or answers will be truly appreciated.

+5
3

Clojure Contrib algo.monad , Scala Option. maybe-m , nil None. :

(ns mulk.monads-test
  (:refer-clojure)
  (:use clojure.repl
        clojure.algo.monads))

(defn function1 [x]
  x)

(defn function2 [x]
  (+ x 10))

(defn function3 [x]
  (* x 2))

(defn calc-stuff [thing]
  (domonad maybe-m
    [x1 (function1 thing)
     x2 (function2 x1)
     x3 (function3 (+ x2 10))]
    x3))

 (calc-stuff 10)   ;=> 60
 (calc-stuff nil)  ;=> nil
+4

You can define a helper function for chaining function calls and checking nil values ​​between:

(defn chain [v & functions]
  (cond (nil? v) nil
        (empty? functions) v
        :else (recur ((first functions) v) (rest functions))))

Then name it like this:

(chain "http://webservice.com" function1 function2 function3 function4)
+1
source

All Articles