将数字转换为数字列表 [英] Convert number to list of digits
本文介绍了将数字转换为数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将数字转换为数字列表?
How do I convert a number to a list of digits?
我目前正在做的:
;; (num->list 12345) -> '(1 2 3 4 5)
(define (num->list n)
(local
((define (num->list n)
(map (lambda (c)
(char->num c))
(string->list (number->string n))))
(define (char->num c)
(- (char->integer c) 48)))
(num->list n)))
但想知道是否有更好的方法.
but would like to know if there's a better way.
推荐答案
这是digits 我的标准序曲的功能:
This is the digits function of my Standard Prelude:
(define (digits n . args)
(let ((b (if (null? args) 10 (car args))))
(let loop ((n n) (d '()))
(if (zero? n) d
(loop (quotient n b)
(cons (modulo n b) d))))))
您的函数版本在字符串和数字之间来回切换;我的版本纯粹是算术.我的版本还提供十进制以外的基数.
Your version of the function goes back-and-forth between strings and numbers; my version is purely arithmetic. My version also provides for bases other than decimal.
这篇关于将数字转换为数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文