如何在Scheme Lisp中将字符串转换为准确的数字? [英] How can I convert a string into exact number in Scheme Lisp?

查看:683
本文介绍了如何在Scheme Lisp中将字符串转换为准确的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下字符串:"6119726089.12814713"

For example, I have this string: "6119726089.12814713"

如果我执行(string->number "6119726089.12814713")-使用SISC实现,结果为6.119726089128147e9-在Guile实现中为6119726089.128147,但我想要一个准确的数字,例如:611972608912814713/100000000,不损失精度.

If I do (string->number "6119726089.12814713") - using the SISC implementation the result is 6.119726089128147e9 - and in Guile implementation is 6119726089.128147 but I would like an exact number, like: 611972608912814713/100000000 without loss precision.

我想要一个类似(string-> exact)之类的函数.

I'd like a function like (string->exact) or something like this.

注意:请修正我的非母语英语并删除此消息.谢谢.

NOTE: please fix my non-native English and remove this message. Thanks.

推荐答案

使用(string->number "#e6119726089.12814713")精确解析数字.这至少适用于球拍和桂尔.但是,它可能无法在其他Scheme实现上正常工作.他们可以先将其解析为不精确,然后再进行转换.

Use (string->number "#e6119726089.12814713") to parse the number as exact. This works for at least Racket and Guile. It may not work correctly on other Scheme implementations, however; they are at liberty to parse as inexact first, then convert.

这是OP要求的string->exact函数的可移植实现.我已经使用多种输入对它进行了手动测试,但是您应该进行自己的测试以确保它符合您的需求:

Here's a portable implementation of the string->exact function that the OP asked for. I've manually tested it with a range of inputs, but you should do your own testing to ensure it fits your needs:

(define (string->exact str)
  (define zero (char->integer #\0))
  (let loop ((result #f)
             (factor 1)
             (seen-dot? #f)
             (digits (string->list str)))
    (if (null? digits)
        (and result (/ result factor))
        (let ((cur (car digits))
              (next (cdr digits)))
          (cond ((and (not result) (not seen-dot?) (char=? cur #\-))
                 (loop result (- factor) seen-dot? next))
                ((and (not seen-dot?) (char=? cur #\.))
                 (loop result factor #t next))
                ((char<=? #\0 cur #\9)
                 (loop (+ (* (or result 0) 10) (- (char->integer cur) zero))
                       (if seen-dot? (* factor 10) factor)
                       seen-dot? next))
                (else #f))))))

这篇关于如何在Scheme Lisp中将字符串转换为准确的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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