Example:
(deftest p09-pack (is (= '( ( a a a a) ( b) ( c c) ( a a) ( d) ( e e e e)) (pack '( a a a a b c c a a d e e e e)))))
Solution:
The key to the solution was the partition-by function. I believe I first learnt about it when looking at other people's solutions to a previous problem (While I find it helpful and enlightening to look at other people's code, I am quite strict about not peeking at solutions to problems I have not solved myself yet.)
Partition-by is a higher-order function that takes a grouping function as it's first argument. It pipes all values through that function and lumps the values together in a subsequence (read sublist) until the grouping functions returns a new value—which marks the start of the next subsequence.
By choosing the identity as our grouping function we get exactly the desired result.
No comments:
Post a Comment