tonumber函数(tonumber'(一二三)-->123 [英] Tonumber function (tonumber ‘(one two three) --> 123
问题描述
解决后如何在球拍中拼写一个数字?(spellNum) ,现在我正在尝试编写一个与此函数相反的函数.即
After the solution of how to spell a number in racket? (spellNum) ,now I am trying to write a function which is opposite of this function. i.e
(tonumber ‘(one two three) --> 123
到目前为止我已经编写了这个工作代码
so far I have written this working code
(define (symbol->digit n)
(case n
('zero 0)
('one 1)
('two 2)
('three 3)
('four 4)
('five 5)
('six 6)
('seven 7)
('eight 8)
('nine 9)
(else (error "unknown symbol:" n))))
(define (numlist n)
(map symbol->digit n))
(numlist '(one two three))
从 numlist 中,我得到了 '(1 2 3).但是下面的函数存在一些问题,我想将列表转换为数字
From numlist, I got '(1 2 3). But to there is some problem in the function below in which I want to convert list to number
(define (list->number l)
(set! multiplier (* 10 (lenght l)))
(for/list [(c l)]
(* multiplier c))
(set! multiplier (/ multiplier 10)))
(list->number '(1 2 3))
任何帮助将不胜感激.我在网上找不到所有类型的循环的文档.在http:///docs.racket-lang.org/ts-reference/special-forms.html?q=loop#%28part._.Loops%29
any help will be appreciated. I can't find documentation of all kind of loops online. at http://docs.racket-lang.org/ts-reference/special-forms.html?q=loop#%28part._.Loops%29
我想熟悉 Racket,所以我想避免内置转换函数.在列表-> 数字中,我试图从列表中一个一个地取数字,然后我想根据列表的长度将它们乘以 10,100,1000 等等.以便它可以返回一个数字.例如 '(1 2 3) = 1*100+2*10+3*1
I want to become familiar with Racket so I want to avoid builtin conversion functions. In list->number,I am trying to take digits one by one from list and then i want to multiply them with 10,100,1000 so on depending on the length of list. so that it can return a number. For example '(1 2 3) = 1*100+2*10+3*1
推荐答案
这里与我的之前的解决方案完全相反,再次对 list->number
过程使用尾递归:
Here's the exact opposite of my previous solution, once again using tail recursion for the list->number
procedure:
(define (symbol->digit n)
(case n
('zero 0)
('one 1)
('two 2)
('three 3)
('four 4)
('five 5)
('six 6)
('seven 7)
('eight 8)
('nine 9)
(else (error "unknown symbol:" n))))
(define (list->number lst)
(let loop ((acc 0) (lst lst))
(if (null? lst)
acc
(loop (+ (car lst) (* 10 acc)) (cdr lst)))))
(define (toNumber lst)
(list->number (map symbol->digit lst)))
它按预期工作:
(toNumber '(four six seven))
=> 467
只是为了好玩,在 Racket 中,我们可以使用 迭代和理解.即便如此,请注意我们不会在任何地方使用 set!
,改变状态是 Python 等语言的规范,但在一般的 Scheme 和 Racket 中,我们尽量避免修改循环内的变量 -有更优雅的方式来表达解决方案:
Just for fun, in Racket we can write a function like list->number
using iteration and comprehensions. Even so, notice that we don't use set!
anywhere, mutating state is the norm in a language like Python but in Scheme in general and Racket in particular we try to avoid modifying variables inside a loop - there are more elegant ways to express a solution:
(define (list->number lst)
(for/fold ([acc 0]) ([e lst])
(+ e (* 10 acc))))
这篇关于tonumber函数(tonumber'(一二三)-->123的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!