exercism / exercism/website-copy

[Question] Why not use string-based solution on Armstrong's number, Clojure track?

Open
#1,942 2 comments 0 reactions 0 assignees View on GitHub
track/clojure type/mentor-notes
Dominant language
HTML
Stars
217
Forks
944
PR merge metrics
No merged PRs in 30d

Description

[The mentoring note](https://github.com/exercism/website-copy/blob/main/tracks/clojure/exercises/armstrong-numbers/mentoring.md) says:

> Most users seem to split the number into digits by iterating a string and parsing characters. Suggest that this can be done arithmetically as well.

But compare this:

```clojure
(defn num->digits [n]
(->> n
(iterate #(quot % 10))
(take-while pos?)
(map #(rem % 10))))

(defn num->digits-rev [n]
(map
#(Character/digit % 10)
(str n)))
```

I can't look at this and say `num->digits` should be preferred in any way:

- Readability speaking IMO the latter is simpler thus more readable, I know the use of `->>` is probably more idiomatic in Clojure, but if that means writing more compliated code, does it worth it?
- Operationally the former takes more step, one has to think about stream manipulations rather than just break that apart with `str` and work on each individual pieces.
- In addition, the backbone data structure is lazy sequence vs. String - to be fair I don't know the details about lazy sequence but my Haskell mental model is telling me to expect little to none allocation (assuming this sequence is then immediately followed by exponentiation and consumed by summation) vs. String-based char buffer allocation. But on the other hand the lazy sequence impose a data dependency as to produce a digit will require knowing all previous results but there's nothing preventing String-based to have some parallelism after `str` is done - plus `toString()` attempts to breakdown by `100` ([see getChars()](https://github.com/openjdk/jdk16/blob/48d8650ae187821d0e79f7353c2f039518e313b1/src/java.base/share/classes/java/lang/Integer.java#L493-L525)) rather than `10` - I'd say using `str` rather than breaking the number down by `10` manually is a performance gain.

In fact I believe in the opposite - the conciseness of string-based approach in comparison to `->>` just proved string-based works better for this particular case.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.