Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
410 - PurelyFunctional.tv Newsletter

Nested lists

Write a function that nests the elements of a list one level deeper by repeating that element inside a new list a given number of times.

Examples

(nest [:a :b :c] 2) ;=> ((:a :a) (:b :b) (:c :c))
(nest [] 10) ;=> ()
(nest [1 2 3 4] 1) ;=> ((1) (2) (3) (4))
(nest [1 2 3] 0) ;=> (()()())

Thanks to this site for the challenge idea where it is considered Hard in Java.

Please submit your solutions as comments on this gist.

@steffan-westcott
Copy link

steffan-westcott commented Jan 20, 2021

@Toni-zgz Welcome to Clojure! Since you asked for some suggestions:

  • To write formatted Clojure code in Github comments, write ```clojure as the first line and ``` as the last line. See the Github docs on syntax hightlighting
  • map on an empty collection will evaluate to an empty sequence. You don't need to explicitly check for an empty input collection in your answer.

@Toni-zgz
Copy link

Toni-zgz commented Jan 20, 2021

@steffan-westcott thanks for your suggestions

@prairie-guy
Copy link

prairie-guy commented Apr 7, 2021

(defn nest [ns k] (map (partial repeat k) ns))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment