1
\$\begingroup\$

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"}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 31, 2017 at 21:00
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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 {})))
answered Feb 3, 2017 at 2:17
\$\endgroup\$
1
  • \$\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\$ Commented Aug 8, 2018 at 22:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.