【问题标题】:Scheme Beginning Student, Function Body Extra Part方案初学者,功能体额外部分
【发布时间】:2014-09-22 19:35:17
【问题描述】:

我尝试遵循this question 中提供的解决方案,但它根本不起作用。

基本上,我的函数是这样工作的:

(define (item-price size normal-addons premium-addons discount)
  (define price 0)
  (+ price (* normal-addon-cost normal-addons) (* premium-addon-cost premium-addons) size)
  (cond
    .. some conditions here
    [else price]))

但是,我遇到了以下错误:

define: expected only one expression for the function body, but found 2 extra parts

现在,我尝试将函数体包装在“开始”中,但是在运行时它声称“开始”未定义。我使用的是初学者学生语言版本,而不是直截了当的球拍。对解决方法有任何见解吗?

【问题讨论】:

  • 当心:(+ price ...) 行没有按照您的想象进行。它正在计算一个值,但该值丢失了,因为您没有分配它 - price 的值没有被更新!

标签: scheme racket racket-student-languages


【解决方案1】:

问题依然存在:在所使用的语言中,我们不能在函数体中编写多个表达式,不能使用 begin 打包多个表达式,以及 letlambda(这将允许我们创建本地绑定)是被禁止的。这是很多限制,但我们可以使用每次计算价格的辅助函数来解决:

(define normal-addon-cost 10)   ; just an example
(define premium-addon-cost 100) ; just an example

(define (price size normal-addons premium-addons)
  (+ (* normal-addon-cost normal-addons)
     (* premium-addon-cost premium-addons) 
     size))

(define (item-price size normal-addons premium-addons discount)
  (cond
    ... some conditions here ...
    [else (price size normal-addons premium-addons)]))

或者:如果price 只使用一次,只需内联计算它的表达式,就不需要创建局部变量或辅助函数。

【讨论】:

  • 我希望不会是这样。嗯,我已经成功了。感谢您的帮助!
猜你喜欢
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2017-06-27
相关资源
最近更新 更多