Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Clojure

Idiom #225 Declare and use an optional argument

Declare an optional integer argument x to procedure f, printing out "Present" and its value if it is present, "Not present" otherwise

(defn f [& [x]]
  (if (integer? x)
    (println "Present" x)
    (println "Not present")))

Optional argument with positional parameters
(defn f 
  ([] (println "Not present"))
  ([x] (println "Present" x)))

Optional argument with pattern matching
#include <optional>
#include <iostream>
void f(std::optional<int> x = {}) {
  std::cout << (x ? "Present" + std::to_string(x.value()) : "Not Present");
}

c++ 17

New implementation...
< >
tkoenig