如何编写一个使用Racket将数字提升到10倍的功能?

时间:2016-03-06 10:54:10

标签: functional-programming scheme racket

这就是我所拥有的:

(define (10th-power 10 y)
 (if (= y 0)
 1
 (* 10 ((10th-power 10 (- y 1)))))

例如,如果我输入2,它应该给出1024。

3 个答案:

答案 0 :(得分:3)

这个简短的程序有很多错误。以下是球拍报告的错误:

  • read: expected a ')' to close '('因为您缺少结束parentheis
  • define: not an identifier... in 10因为10不能是变量名,所以不能在参数列表中。
  • application: not a procedure。递归部分中的双括号使得10th-power的结果作为结果尝试作为结果,而不是仅使用该值。

如果您修复了这些问题,那么您的程序就会有效,但它会执行10^y而不是y^10。也许你需要一个助手,你可以保持你的乘数y倍数而不是y,这应该是10的位置。

答案 1 :(得分:1)

你很亲密:

#lang racket

(define (10th-power y)
  (if (= y 0)
      1
      (* 10 (10th-power (- y 1)))))

(10th-power 3)

注意事项:您无法在表达式周围插入额外的括号。示例:(100)表示调用100而不带参数 - 并且由于100不是函数,因此您得到错误"应用程序:不是过程:。

要注意的第二件事:你不需要10作为参数。

答案 2 :(得分:0)

你可以这样写一个递归:

#lang racket
(define (10th-power y)
  (if (= y 0 )
      1
      (* 10 (10th-power (- y 1)))))
顺便说一句,如果你想提高从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)