August 22, 2018
Just Juxt #8: Split a sequence (4clojure #49)
Write a function which will split a sequence into two parts.
...but without using split-at
.
(ns live.test
(:require [cljs.test :refer-macros [deftest is testing run-tests]]))
(defn chop [n coll]
)
(deftest test-49
(is (= (chop 3 [1 2 3 4 5 6]) [[1 2 3] [4 5 6]]))
(is (= (chop 1 [:a :b :c :d]) [[:a] [:b :c :d]]))
(is (= (chop 2 [[1 2] [3 4] [5 6]]) [[[1 2] [3 4]] [[5 6]]])))
(run-tests)
These kinds of problems are interesting, and my first inclination is to "cheat" by looking up the source for split-at
:
user=> (source split-at)
(defn split-at
"Returns a vector of [(take n coll) (drop n coll)]"
{:added "1.0"
:static true}
[n coll]
[(take n coll) (drop n coll)])
There we have it, the "official" implementation. A function that returns a vector containing the result of calling take
and drop
on a coll
. Sound familiar?
(defn chop [n coll]
((juxt take drop) n coll))
(run-tests)
This one is very straightforward. Breaking it down:
(take 3 [1 2 3 4 5 6])
(drop 3 [1 2 3 4 5 6])
((juxt take drop) 3 [1 2 3 4 5 6])