I had never programmed in a functional programming language before. I think that this function has large nesting. Is there way to rewrite it better? I am most worried about the use of "flatten". Is there way to get rid of it? Also, is the indentation correct and does the function name correspond to Clojure naming style?
(defrecord Point [x y])
(def delimiter #" ")
(defn str->cells
"Converts string with cells separated with
delimiter and new lines to Points hash map"
[^String s]
{:pre [(re-matches #"^((?:^|\s)(?:.|\s)(?=\s|$))+$" s)]}
(apply
hash-map
(flatten
(map-indexed
(fn [y line]
(map-indexed
(fn [x value] [(Point. x y) value])
(str/split line delimiter)))
(str/split-lines s)))))
;; Example of use:
(str->cells "1 2\n3") ;; -> {#Point{:x 1, :y 0} "2", #Point{:x 0, :y 0} #Point{:x 0, :y 1} "3"}
1 Answer 1
Since there is no answers, I'll post my new version of code:
(defn line->cells
"Converts string with cells to sequence of maps of Points
It is str->cells helper, so it requires y argument."
[str->value ^Long y ^String line]
{:pre [(re-matches #"^((?:^| )(?:.+?| )(?= |$))+$" line)]}
(map-indexed
(fn [x value] {(Point. x y) (str->value value)})
(str/split line #" ")))
(defn str->cells
"Converts string with cells separated with
delimiter and new lines to Points hash map"
[^String s str->value]
{:pre [(re-matches #"^((?:^|\s)(?:.+?| )(?=\s|$))+$" s)]}
(->> s
(str/split-lines)
(map-indexed (partial line->cells str->value))
(flatten)
(into {})))
-
\$\begingroup\$ Bearing in mind that you answered your own question, you have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that other readers can learn from your thought process. Please read Why are alternative solutions not welcome? \$\endgroup\$2018年08月08日 22:20:38 +00:00Commented Aug 8, 2018 at 22:20
Explore related questions
See similar questions with these tags.