将自然数转换为特定的基数并将其作为列表返回

编程入门 行业动态 更新时间:2024-10-18 22:34:26
本文介绍了将自然数转换为特定的基数并将其作为列表返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想将函数的结果显示为列表而不是数字.我的结果是:

I want to show the result of my function as a list not as a number. My result is:

(define lst (list )) (define (num->base n b) (if (zero? n) (append lst (list 0)) (append lst (list (+ (* 10 (num->base (quotient n b) b)) (modulo n b))))))

出现下一个错误:

expected: number? given: '(0) argument position: 2nd other arguments...: 10

推荐答案

我认为你必须重新考虑这个问题.将结果附加到全局变量绝对不是要走的路,让我们通过尾递归尝试不同的方法:

I think you have to rethink this problem. Appending results to a global variable is definitely not the way to go, let's try a different approach via tail recursion:

(define (num->base n b) (let loop ((n n) (acc '())) (if (< n b) (cons n acc) (loop (quotient n b) (cons (modulo n b) acc)))))

它按预期工作:

(num->base 12345 10) => '(1 2 3 4 5)

更多推荐

将自然数转换为特定的基数并将其作为列表返回

本文发布于:2023-11-29 20:46:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自然数   基数   转换为   列表   并将其

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!