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

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

问题描述

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

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

(. Integer parseInt  numberString)

是否有一种更加 clojuriff 的方式来处理整数和浮点数,并返回 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.

推荐答案

您可以使用 edn 阅读器解析数字.这也有利于在需要时为您提供浮点数或 Bignum.

You can use the edn reader to parse numbers. This has the benefit of giving you floats or Bignums when needed, too.

user> (require '[clojure.edn :as edn])
nil
user> (edn/read-string "0.002")
0.0020

如果你想要一个巨大的数字向量,你可以作弊并这样做:

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

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

虽然有点hacky.或者有 re-seq:

Kind of hacky though. Or there's re-seq:

user> (let [input "5  10  0.002
4  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
4  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天全站免登陆