3 ms·
Your three line version is pretty much equivalent to this part of the Clojure version: (let [x (f (first s))] (if (nil? x) (keep f (res
by jimbokun 14y ago
Your three line version is pretty much equivalent to this part of the Clojure version:
(let [x (f (first s))]
(if (nil? x)
(keep f (rest s))
(cons x (keep f (rest s)))))
The rest of it appears to be performance optimizations, that probably make sense for a key function in the core library likely to be commonly invoked.
- dschiptsov 14y agoThere are some subtle differences, which makes the whole sense. Classic version has a self-evident clarity and familiar shape of a recursive function, which utilizes TCO. Perfection is achieved when there is nothing more to cut off, not when there is nothing more to pile up.)
- Evbn 14y agoNothing more to cut off, including runtime and memory usage.
- rapala 14y agoSo the classic version works in a lazy fashion, for example with infinite structures? Keep in mind that Clojure is a strict language by default.
- spacemanaki 14y agoIs the classic one actually going to be able to leverage tail-call elimination? Obviously it could be refactored to make a tail-recursive call, but correct me if I'm wrong, it wouldn't be automatic. After refactoring it, the tail-recursive version would be a bit harder to read than the naive implementation. In a sense the Clojure code is in the same boat, it's just that the optimizations are more complicated, because it's not working with singly linked lists in the "address register" and "decrement register".