Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a clojure string of numbers into separate integers?

Tags:

clojure

I can read some data in like this in the repl. For a real program I plan to assign in a let special form.

(def x1 (line-seq (BufferedReader. (StringReader. x1))))

If I enter 5 5, x1 is bound to ("5 5")

I would like to convert this list of one element into a list of two integers. How can I do that? I have been playing around with parsing the string on whitespace, but am having trouble performing the conversion to integer.

like image 988
octopusgrabbus Avatar asked Dec 08 '11 18:12

octopusgrabbus


2 Answers

Does this help? In Clojure 1.3.0:

(use ['clojure.string :only '(split)])
(defn str-to-ints
  [string]
  (map #(Integer/parseInt %)
        (split string #" ")))
(str-to-ints "5 4")
; => (5 4)
(apply str-to-ints '("5 4"))
; => (5 4)

In case the Clojure version you're using doesn't have clojure.string namespace you can skip the use command and define the function in a following way.

(defn str-to-ints
  [string]
  (map #(Integer/parseInt %)
        (.split #" " string)))

You can get rid of regular expressions by using (.split string " ") in the last line.

like image 100
Jan Avatar answered Nov 02 '22 12:11

Jan


Works for all numbers and returns nil in the case it isn't a number (so you can filter out nils in the resulting seq)

(require '[clojure.string :as string])

(defn parse-number
  "Reads a number from a string. Returns nil if not a number."
  [s]
  (if (re-find #"^-?\d+\.?\d*$" s)
    (read-string s)))

E.g.

(map parse-number (string/split "1 2 3 78 90 -12 0.078" #"\s+"))
; => (1 2 3 78 90 -12 0.078)
like image 32
solussd Avatar answered Nov 02 '22 13:11

solussd