Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot have first parameter as optional

Can you have a function with and optional parameter as the first and only parameter?

thus

(defn foo [& bar] (if (= bar) 1 2))

like image 649
KArneaud Avatar asked Feb 15 '26 01:02

KArneaud


1 Answers

What & bar means at function definition is that all the rest of the arguments will be put into a list. It does not give any guarantees as to the size of the list, so it could be empty, with one or more items.

A better approach to having one and only optional argument, is to have it accept zero or one arguments:

(defn foo
   ([]    (foo 12))
   ([bar] (if (= bar 12) 1 2)))

In this example, if you call the first function definition, with zero arity, it will simply call the second 1-arity function definition with a default value of 12.

like image 168
Shlomi Avatar answered Feb 18 '26 11:02

Shlomi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!