Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure way on flow control statement

Tags:

clojure

Suppose I have a python function like this:

def required(value):
    if value is None:
        throw Exception
    if isintance(value, str) and not value:
        throw Exception
    return value

Basically I want to check if the value is null or not. If the value is a String, also check if it's empty or not.

What is the clojure way of doing something like this?

like image 263
Budi Sutrisno Avatar asked Jun 16 '26 22:06

Budi Sutrisno


2 Answers

The Clojure way of doing something like this is not to throw exceptions or so. The idiomatic way would be something that returns nil and nothing else.

So my advise: Do this without exceptions.

Your function will then look like this:

(defn required [value]
  (when (string? value)
    value))

It checks for the type of value and returns nil if it is not a String. Otherwise return your value.

Or if you want an error message in your terminal:

(defn required [value]
  (if (string? value)
    value
    (println "Value must be a String.")))

Note that println prints the String and then returns again nil.

like image 155
n2o Avatar answered Jun 21 '26 20:06

n2o


Preconditions would do the trick nicely in this instance. Otherwise use Clojure's control flow special forms/macros, e.g. if, cond with throw.

user=> (defn required 
         [value] 
         {:pre [(string? value) (not-empty value)]} 
         value)
#'user/required

user=> (required nil)
AssertionError Assert failed: (string? value)  user/required ...

user=> (required "")
AssertionError Assert failed: (not-empty value) ...

user=> (required "foo")
"foo"
like image 31
5 revsA. Webb Avatar answered Jun 21 '26 22:06

5 revsA. Webb