列出方案编号 [英] Scheme number to list

查看:130
本文介绍了列出方案编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为我的程序编写一个子程序,该程序需要使用一个整数,例如34109,并将其放入包含元素3、4、1、0、9的列表中.该整数可以是任何长度.有人对此有把戏吗?我已经考虑过在每个地方都使用模,但是我不认为它应该那么复杂.

I need a subroutine for my program written in scheme that takes an integer, say 34109, and puts it into a list with elements 3, 4, 1, 0, 9. The integer can be any length. Does anyone have a trick for this? I've thought about using modulo for every place, but I don't think it should be that complicated.

推荐答案

我能想到的最简单的方法是使用算术运算和

The simplest way I can think of, is by using arithmetic operations and a named let for implementing a tail-recursion:

(define (number->list num)
  (let loop ((num num)
             (acc '()))
    (if (< num 10)
        (cons num acc)
        (loop (quotient num 10)
              (cons (remainder num 10) acc)))))

或者,您可以使用字符串操作解决此问题:

Alternatively, you can solve this problem using string operations:

(define char-zero (char->integer #\0))

(define (char->digit c)
  (- (char->integer c) char-zero))

(define (number->list num)
  (map char->digit
       (string->list (number->string num))))

可以将其压缩为单个函数,但是我相信如果将问题分成上述子部分,则更容易理解.

This can be compressed into a single function, but I believe it's easier to understand if we split the problem in subparts as above.

(define (number->list num)
  (map (lambda (c) (- (char->integer c) (char->integer #\0)))
       (string->list
        (number->string num))))

无论如何,结果是预期的:

Anyway, the results are as expected:

(number->list 34109)
> '(3 4 1 0 9)

这篇关于列出方案编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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