Convert a sequence of strings to integers (Clojure)

最后都变了- 提交于 2019-12-18 03:02:25

问题


I currently am having an issue where I have to read a text file from the command line containing at least one integer. I'm reading the file, doing a regular-expression match to ignore whitespace.

(re-seq #"[0-9]+" (slurp (first *command-line-args*)))

After this I have to write a whole function just to convert this sequence of strings into a sequence of integers. Apparently I cannot map Integer. to the sequence (unless I am using map incorrectly).

Is there some elegant way of handling this, something similar to map? Or do I have to go through recursively popping off first and casting it to Integer. to get this to work?

I am currently learning Clojure, and as I learn bits I am going back and doing little programmer quizzes I used to pick up other languages.


回答1:


You're looking for Integer/parseInt.

user=> (map #(Integer/parseInt %) ["1" "2" "3" "4"])
(1 2 3 4)

You have to wrap Integer/parseInt in an anonymous function because Java methods aren't functions.

read-string would also work in this case:

user=> (map read-string ["1" "2" "3" "4"])
(1 2 3 4)

read-string reads any object from a string, not just integers. So, if you did (read-string "1.0") you'd get back a double. When reading from outside sources, it's usually better to limit what can be read to precisely what you need, which is an integer in this case. Therefore, I recommend using my first example.



来源:https://stackoverflow.com/questions/4714923/convert-a-sequence-of-strings-to-integers-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!