Skip to content

Instantly share code, notes, and snippets.

@ericnormand
Created January 11, 2021 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnormand/965c5004944a62296c481aa9ac3fff5a to your computer and use it in GitHub Desktop.
Save ericnormand/965c5004944a62296c481aa9ac3fff5a to your computer and use it in GitHub Desktop.
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.

@sztamas
Copy link

sztamas commented Jan 12, 2021

@frndmg I see what you're trying to do :-), but for python I would prefer the more idiomatic:

def nest(xs, n):
    return [[x] * n for x in xs]

@ndonolli
Copy link

My clojure solution was essentially identical to many solutions posted here already. So for fun, I'll show an ES6 javascript solution:

const nest = (xs, n) => xs.map(x => new Array(n).fill(x));

@Toni-zgz
Copy link

Toni-zgz commented Jan 17, 2021

My clojure solution. I know isn't the best but i think is clearer than other solutions for beginners as me.

(ns nest)
(require '[clojure.test :as test])

(defn nest [vect num-rep]
    (let [funcion (fn [elt] (repeat num-rep elt))]
        (map funcion vect)))

(test/deftest nest-test
    (test/is (= '((:a :a) (:b :b) (:c :c))  (nest [:a :b :c] 2)))
    (test/is (= '() (nest [] 10)))
    (test/is (= '((1) (2) (3) (4))  (nest [1 2 3 4] 1)))
    (test/is (= '(()()()) (nest [1 2 3] 0))))

(test/run-tests 'nest)

@cristiano-belloni
Copy link

Javascript oneliner for comparison:

(a, n) => a.map(a => new Array(n).fill(a))

@steffan-westcott
Copy link

@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

@steffan-westcott thanks for your suggestions

@prairie-guy
Copy link

(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