5 ms·
+ is a function, there are no operators in Clojure. That allows for some nifty tricks like: (reduce + [1 2 3]) ; returns 6
by kolme 2y ago
+ is a function, there are no operators in Clojure.
That allows for some nifty tricks like:
(reduce + [1 2 3])
; returns 6
- globular-toast 2y agoAnother neat thing is that these functions are n-ary, and that includes 0 args. So (+) => 0 (additive identity) and (*) => 1 (multiplicative identity). Little things like this are missing from languages like Python and make functional programming worse than it should be.
- tasuki 2y agoOh wow, this is truly great! Would you have a link to the code behind `(+)` and `(*)` ? (In my functional programming languages, `reduce` also requires passing an initial value, like `foldl (+) 0 [1, 2, 3]`. But surely it should get a monoid instead of two separate arguments for the operation and the starting value!)
- ReleaseCandidat 2y agoOf course `+` and `*` are special, but defining such functions yourself is possible: https://clojure.org/guides/learn/functions#_multi_arity_functions https://clojure.org/guides/learn/functions#_multi_arity_func... https://clojure.org/guides/learn/functions#_variadic_functions https://clojure.org/guides/learn/functions#_variadic_functio...
- globular-toast 2y agoYeah, it always annoys me to have to pass an initial argument. The idea of identities is built into Lisps and seems conspicuously missing from other languages and I don't know why. In Python and JS people have to write stuff like `lambda x: x` over and over again. The identity function is surely special enough to get its own name.
- tasuki 2y agoThis does not involve an identity function? It's just a textbook monoid: an operation on two elements which produces another (+ or *), with a "neutral" element provided (0 or 1).
- globular-toast 2y agoI know this isn't the identity function, but it's the same idea and a feeling I get when using Lisps that the language is kind of "complete". Including the identity function and having built in 0-ary functions where it makes sense are examples of this.
- kolme 2y agoSource code: +: https://github.com/clojure/clojure/blob/clojure-1.11.1/src/clj/clojure/core.clj#L986 https://github.com/clojure/clojure/blob/clojure-1.11.1/src/c... *: https://github.com/clojure/clojure/blob/clojure-1.11.1/src/clj/clojure/core.clj#L1010 https://github.com/clojure/clojure/blob/clojure-1.11.1/src/c... Docs: +: https://clojuredocs.org/clojure.core/%2B https://clojuredocs.org/clojure.core/%2B *: https://clojuredocs.org/clojure.core/ https://clojuredocs.org/clojure.core/*