2
\$\begingroup\$

Solving a 4Clojure problem, I got this answer to compress a sequence (problem 30):

#(map first (partition-by identity %))

What would be the best approach to have this work with plain numbers too?

My solution was this:

(defmulti comp class)
(defmethod comp java.lang.Long [x] x)
(defmethod comp :default [x] (map first (partition-by identity %)))

The code is more than tripled. Are there better solutions? Shorter? More idiomatic? I tried extending java.lang.Long with ISeqable, but failed miserably.

\$\endgroup\$
1
\$\begingroup\$

Nice solution. Your solution already works great with sequences of numbers (and more) already. The comp multi-method is not a good idea. It is a function which can take either a seq or a number. You should avoid creating functions that take arguments that can be different types (it is confusing and suggests your might be better off with 2 functions or a protocol) unless there is a really good reason. In this case comp does not add anything useful (why did you add it? do you have an example use case?)

\$\endgroup\$
  • \$\begingroup\$ Hey, thanks! There's no real reason, I was just messing a little to learn things :) I agree it doesn't make much sense like this, but I just wanted to try what possible solutions to similar scenarios would be. \$\endgroup\$ – Dario Oddenino Nov 3 '15 at 22:51
  • \$\begingroup\$ Gotcha. If you really want to just check the type of something, also consider just using a test: (if (number? x) x blah) instead of using dispatch. \$\endgroup\$ – Timothy Pratley Nov 3 '15 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.