在clojure中解析数字的最简单的方法是什么? [英] What's the easiest way to parse numbers in clojure?

查看:95
本文介绍了在clojure中解析数字的最简单的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用java来解析数字,例如。

I've been using java to parse numbers, e.g.

(. Integer parseInt  numberString)

有更多的clojuriffic方法,将处理整数和浮点数,并返回clojure数字?我不是特别担心这里的性能,我只是想在文件中处理一堆白色空格分隔的数字,并以最直接的方式做一些事情。

Is there a more clojuriffic way that would handle both integers and floats, and return clojure numbers? I'm not especially worried about performance here, I just want to process a bunch of white space delimited numbers in a file and do something with them, in the most straightforward way possible.

所以文件可能有以下行:

So a file might have lines like:

5  10  0.0002
4  12  0.003

我想将行转换成数字的向量。

And I'd like to be able to transform the lines into vectors of numbers.

推荐答案

如果你确定你的文件只包含数字,你可以使用Clojure读取器来解析数字。这有利于在需要时给你浮动或Bignums。

If you're very sure that your file contains only numbers, you can use the Clojure reader to parse numbers. This has the benefit of giving you floats or Bignums when needed, too.

user> (read-string "0.002")
0.0020

重新解析任意用户提供的输入,因为读取器宏可以用来在读取时执行任意代码和删除硬盘驱动器等。

This isn't safe if you're parsing arbitrary user-supplied input, because reader macros can be used to execute arbitrary code at read-time and delete your hard drive etc.

如果你想要一个巨大的矢量的数字,你可以欺骗和做这:

If you want one huge vector of numbers, you could cheat and do this:

user> (let [input "5  10  0.002\n4  12  0.003"]
        (read-string (str "[" input "]")))
[5 10 0.0020 4 12 0.0030]

或者有 re-seq

user> (let [input "5  10  0.002\n4  12  0.003"]
        (map read-string (re-seq #"[\d.]+" input)))
(5 10 0.0020 4 12 0.0030)

或每行一个向量:

user> (let [input "5  10  0.002\n4  12  0.003"]
        (for [line (line-seq (java.io.BufferedReader.
                              (java.io.StringReader. input)))]
             (vec (map read-string (re-seq #"[\d.]+" line)))))
([5 10 0.0020] [4 12 0.0030])

我相信还有其他方法。

这篇关于在clojure中解析数字的最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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