Avatar of 4d47
0
0
Genius
0
0

4d47's solution

to Flatten Array in the Clojure Track

0
0
Genius
0
0
Instructions
Test suite
Solution

Take a nested list and return a single flattened list with all values except nil/null.

The challenge is to write a function that accepts an arbitrarily-deep nested list-like structure and returns a flattened structure without any nil/null values.

For Example

input: [1,[2,3,null,4],[null],5]

output: [1,2,3,4,5]

Source

Interview Question https://reference.wolfram.com/language/ref/Flatten.html

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

flatten_array_test.clj

(ns flatten-array-test
  (:require [clojure.test :refer [deftest is testing]]
            [flatten-array]))

(deftest flattens-array-of-ints
  (testing "flattens array with just integers present"
    (is (= [1 2 3 4 5 6 7 8]
           (flatten-array/flatten [1 [2 3 4 5 6 7] 8])))))

(deftest five-level-nesting
  (testing "5 level nested list"
    (is (= [0 2 2 3 8 100 4 50 -2]
           (flatten-array/flatten [0 2 [[2 3] 8 100 4 [[[50]]]] -2])))))

(deftest six-level-nesting
  (testing "6 level nested list"
    (is (= [1 2 3 4 5 6 7 8]
           (flatten-array/flatten [1 [2 [[3]] [4 [[5]]] 6 7] 8])))))

(deftest six-level-nested-with-nils
  (testing "6 level nested list with nil values"
    (is (= [0 2 2 3 8 100 -2]
           (flatten-array/flatten [0 2 [[2 3] 8 [[100]] nil [[nil]]] -2])))))

(deftest all-nils-list
  (testing "All values in nested list are nil"
    (is (empty?
          (flatten-array/flatten [nil [[[nil]]] nil nil [[nil nil] nil] nil])))))
(ns flatten-array
  (:refer-clojure :rename {flatten flat}))

(defn flatten [x]
  (filter some? (flat x)))

What can you learn from this solution?

A huge amount can be learnt from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that I could read more about to develop my understanding?