将字符串序列转换为整数(Clojure) [英] Convert a sequence of strings to integers (Clojure)

查看:284
本文介绍了将字符串序列转换为整数(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*)))

必须写一个完整的函数,只是将这个字符串序列转换为一个整数序列。显然我不能映射整数。到序列(除非我不正确地使用映射)。

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?

我目前正在学习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 从字符串读取任何对象,而不仅仅是整数。所以,如果你(读字符串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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆