Convert a sequence of strings to integers (Clojure)

前端 未结 1 948
时光取名叫无心
时光取名叫无心 2020-12-15 16:36

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 matc

相关标签:
1条回答
  • 2020-12-15 17:31

    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.

    0 讨论(0)
提交回复
热议问题