如何在球拍中拼写数字?(法术编号) [英] how to spell a number in racket? (spellNum)

查看:55
本文介绍了如何在球拍中拼写数字?(法术编号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Racket 的新手,我想编写一个函数 spellNum 来执行此操作:

I am new to Racket and I want to write a function spellNum which does this:

(spellNum 467) ---> '(four six seven)

我不知道如何开始.我是通过查看在线文档开始编程的,但我不知道如何在 Dr Racket 中声明变量.我基本上是一个 Python 人.有人可以推动我编写此功能吗?

I don't know how to start. I have started programming by seeing the online documentation, but I don't know how to declare a variable in Dr Racket. I am basically a Python guy. can somebody give me a push to program this function?

(define (spellNum n)
  (if (number? n)
    (what should I do ?)
      null))

推荐答案

已经发布了一个完整的解决方案,所以我想我可以向您展示如何编写一个惯用程序.请注意,number->list 使用一种称为尾递归的技术来有效地表达循环.尽管(来自 Python 背景)使用显式循环构造(如@uselpa 的回答所示)可能很诱人,但要真正体现 Scheme 的精神,您应该学习如何使用递归编写循环,这是标准方法用这种语言表达迭代(在罗马时,像罗马人那样做):

A complete solution has been posted, so I guess it's ok for me to show you how to write an idiomatic procedure. Notice that number->list uses a technique called tail recursion for efficiently expressing a loop. Although (coming from a Python background) it might be tempting to use an explicit looping construct (as shown in @uselpa's answer), to really get in the spirit of Scheme you should learn how to write a loop using recursion, it's the standard way to express iteration in this language (When in Rome, do as the Romans do):

(define (digit->symbol n)
  (case n
    ((0) 'zero)
    ((1) 'one)
    ((2) 'two)
    ((3) 'three)
    ((4) 'four)
    ((5) 'five)
    ((6) 'six)
    ((7) 'seven)
    ((8) 'eight)
    ((9) 'nine)
    (else (error "unknown digit:" n))))

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

(define (spellNum n)
  (map digit->symbol (number->list n)))

诀窍是将问题分成不同的部分,digit->symbol 将单个数字转换为符号.类似地,number->list 将数字转换为数字列表.编写这些辅助程序后,很容易编写 spellNum,它按预期工作:

The trick is to split the problem in different parts, digit->symbol converts a single digit into a symbol. Similarly, number->list transforms a number into a list of numbers. After writing those helper procedures it's easy to write spellNum, which works as expected:

(spellNum 467)
=> '(four six seven)

这篇关于如何在球拍中拼写数字?(法术编号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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