如何使用 Racket 编写将数字提高到 10 次方的函数?
How to write a function that raises a number to 10th power using Racket?
这是我的:
(define (10th-power 10 y)
(if (= y 0)
1
(* 10 ((10th-power 10 (- y 1)))))
例如,如果我输入 2,它应该给出 1024。
这个简短的过程中有很多错误。以下是球拍报告的错误:
read: expected a ')' to close '('
因为您缺少结尾括号
define: not an identifier... in 10
因为 10 不能是变量名,所以不能在参数列表中。
application: not a procedure
。递归部分中的双括号使 10th-power
的结果作为过程尝试作为结果,而不是仅按原样使用值。
如果您修复了这些问题,您的程序将会运行,但它会执行 10^y
而不是 y^10
。也许您需要一个帮手,您可以在其中保留乘以 y
的次数,而不是 y
,后者应该是 10 位。
你很接近:
#lang racket
(define (10th-power y)
(if (= y 0)
1
(* 10 (10th-power (- y 1)))))
(10th-power 3)
注意事项:不能在表达式两边插入额外的括号。示例:(100)
表示不带参数调用 100 - 由于 100 不是函数,因此您会收到错误消息“应用程序:不是过程:.
要注意的第二件事:您不需要将 10 作为参数。
你可以这样写递归:
#lang racket
(define (10th-power y)
(if (= y 0 )
1
(* 10 (10th-power (- y 1)))))
顺便说一句,如果你想把你的space效率从o(n)提高到o(1),你可以写迭代:
#lang racket
(define (10th-power y)
(define (iter back times)
(if (= times 0)
back
(iter (* 10 back) (- times 1))))
(iter 1 y))
(10th-power 3)
这是我的:
(define (10th-power 10 y)
(if (= y 0)
1
(* 10 ((10th-power 10 (- y 1)))))
例如,如果我输入 2,它应该给出 1024。
这个简短的过程中有很多错误。以下是球拍报告的错误:
read: expected a ')' to close '('
因为您缺少结尾括号define: not an identifier... in 10
因为 10 不能是变量名,所以不能在参数列表中。application: not a procedure
。递归部分中的双括号使10th-power
的结果作为过程尝试作为结果,而不是仅按原样使用值。
如果您修复了这些问题,您的程序将会运行,但它会执行 10^y
而不是 y^10
。也许您需要一个帮手,您可以在其中保留乘以 y
的次数,而不是 y
,后者应该是 10 位。
你很接近:
#lang racket
(define (10th-power y)
(if (= y 0)
1
(* 10 (10th-power (- y 1)))))
(10th-power 3)
注意事项:不能在表达式两边插入额外的括号。示例:(100)
表示不带参数调用 100 - 由于 100 不是函数,因此您会收到错误消息“应用程序:不是过程:.
要注意的第二件事:您不需要将 10 作为参数。
你可以这样写递归:
#lang racket
(define (10th-power y)
(if (= y 0 )
1
(* 10 (10th-power (- y 1)))))
顺便说一句,如果你想把你的space效率从o(n)提高到o(1),你可以写迭代:
#lang racket
(define (10th-power y)
(define (iter back times)
(if (= times 0)
back
(iter (* 10 back) (- times 1))))
(iter 1 y))
(10th-power 3)