Last active
June 2, 2017 06:03
-
-
Save charliegriefer/1c8552ac9676ad247691cbec3bf6920c to your computer and use it in GitHub Desktop.
The Elegance of Clojure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ;; For a given list with N integers, return a new list removing the elements at odd positions. | |
| ;; Source: https://www.hackerrank.com/challenges/fp-filter-positions-in-a-list | |
| ;; My solution: | |
| (fn[lst] | |
| (map | |
| #(when ((comp odd? first) %) | |
| (println (second %))) | |
| (map-indexed list lst))) | |
| ;; A _much_ more elegant solution: | |
| (fn [lst] | |
| (map second (partition 2 lst))) |
Author
Author
Just had a shower thought. Literally, came to me as I was shampooing my beard.
(fn [lst]
(rest (take-nth 2 (conj coll 0))))
user=> (rest (take-nth 2 (conj '(8 15 22 1 10 6 2 18 18 1) 0)))
;; => (15 1 6 18 1)
I'll break it down later.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's worth pointing out that, for this particular problem, the elegant solution only works with an even number of elements in the original collection. With an odd number, and using
partitionwith annof 2, the last element of the original collection is dropped.It's an easy enough fix:
For example:
This returns a new collection as a
vector, but that's necessary, asconj'ing a new value to a list will place the new value at the beginning:The vector is treated the same as the list in the function in the gist.
Clojure does keep you on your toes :)