Skip to content

Instantly share code, notes, and snippets.

@charliegriefer
Last active June 2, 2017 06:03
Show Gist options
  • Select an option

  • Save charliegriefer/1c8552ac9676ad247691cbec3bf6920c to your computer and use it in GitHub Desktop.

Select an option

Save charliegriefer/1c8552ac9676ad247691cbec3bf6920c to your computer and use it in GitHub Desktop.
The Elegance of Clojure
;; 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)))
@charliegriefer
Copy link
Author

charliegriefer commented Jun 1, 2017

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 partition with an n of 2, the last element of the original collection is dropped.

It's an easy enough fix:

(conj (vec lst) 0)

For example:

user=> (conj (vec '(1 2 3)) 0)
;; => [1 2 3 0]

This returns a new collection as a vector, but that's necessary, as conj'ing a new value to a list will place the new value at the beginning:

user=> (conj '(1 2 3) 0)
;; => (0 1 2 3)

The vector is treated the same as the list in the function in the gist.

Clojure does keep you on your toes :)

@charliegriefer
Copy link
Author

charliegriefer commented Jun 1, 2017

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