将字符串序列转换为整数 (Clojure) [英] Convert a sequence of strings to integers (Clojure)
问题描述
我目前遇到一个问题,我必须从命令行读取至少包含一个整数的文本文件.我正在阅读文件,进行正则表达式匹配以忽略空格.
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*)))
在此之后,我必须编写一个完整的函数来将这个字符串序列转换为一个整数序列.显然我无法将 Integer.
映射到序列(除非我使用的映射不正确).
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).
是否有一些优雅的处理方式,类似于地图?或者我是否必须先递归弹出并将其转换为 Integer.
才能使其工作?
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?
我目前正在学习 Clojure,当我学习一些知识时,我会回去做一些以前学习其他语言的程序员小测验.
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.
推荐答案
您正在寻找 Integer/parseInt
.
user=> (map #(Integer/parseInt %) ["1" "2" "3" "4"])
(1 2 3 4)
您必须将 Integer/parseInt
包装在匿名函数中,因为 Java 方法不是函数.
You have to wrap Integer/parseInt
in an anonymous function because Java methods aren't functions.
read-string
也适用于这种情况:
user=> (map read-string ["1" "2" "3" "4"])
(1 2 3 4)
read-string
从字符串中读取任何 对象,而不仅仅是整数.所以,如果你做了 (read-string "1.0")
你会得到双倍的回报.从外部资源读取时,通常最好将可以读取的内容限制为您需要的内容,在这种情况下为整数.因此,我建议使用我的第一个示例.
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.
这篇关于将字符串序列转换为整数 (Clojure)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!