How do I convert a string into two integers in Clojure?
A json-encoded string is passed into my function, and I need to split that string based on a delimiter, then convert the first two delimited values into integers and assign them to variables which will be used within the functio开发者_JAVA技巧n. I've got code that works, though it looks clumsy to me.
(:use [clojure.string :only (split trim)])
(:use [clojure.data.json :only (json-str write-json read-json)])
(defn parse-int [s] (Integer. (re-find #"[0-9]*" s)))
(map parse-int (take 2
(map trim (seq (.split #"\|"
(read-json "\" 123 | 456 | 789 \""))))))
I've hard-coded my sample input value for simplicity and so it's easily reproduced in a REPL.
I expect the result: (123 456)
(which, in my code, is assigned to (let [[a b]
)
As I said, this code works, but I feel I must be missing something that would make it less ugly, more idiomatic.
I think this is clearer:
(:use [clojure.string :only (split trim)])
(:use [clojure.data.json :only (read-json)])
(map #(Integer/valueOf (trim %))
(split (read-json input) #"\|"))
assuming input
is your input string.
Integer/valueOf
(alternatively Integer/parseInt
) seems to be the main thing your missing. No need for regex.
精彩评论