Is there any reasonable way to check function input in Clojure?

I am writing a simple DiceRoller application and I created the main function, however, I am wondering if there is a β€œsmart” way to check function inputs in Clojure instead of using conditional branch expressions to validate input? My function is below with a sample test, I will also need to check if n is not a number with another, if or or, and it feels dirty.

Also, if someone could point out a smarter way to execute this function, I would appreciate any feedback, this is my first attempt to try to functionally program

(ns DiceRoller) (defn roll "rolls a specified number of n sided dice " ([] (roll 1 6)) ([number] (roll number 6)) ([number n] (if-not number? number (throw (IllegalArgumentException. (str "incorrect input, integers only")))) (take number (repeatedly #(+ (rand-int n) 1))) ) ) 
+7
source share
2 answers

Basically, the Clojure attitude is "just suppose you got it right." In this case, if you completely withdraw your check, the user will end up with the same exception. But if you really wanted to do it, you have to do it right! Right now, your code throws an exception on every input because you are missing the partners around (number? number) .

+7
source

Of course there is - for this you can use the statement :pre .

 (defn some-fun [x] {:pre [(number? x)]} (foo x)) 

Now you will get the AssertionError Assert crash: (number? X) if you pass the function a non-numeric argument x .

Checking if the input is a number is useless, as @amalloy has already been mentioned, but there are many fully justified premises (and, if accepted at all) that you might want to apply to your function. Here you can see more detailed information on the topic here and here .

+22
source

All Articles