schemeracketracket-student-languages

Scheme Beginning Student, Function Body Extra Part


I attempted to follow the solution provided in this question, but it simply didn't work.

Essentially, my function works like so:

(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]))

However, I am met with the following error:

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

Now, I've tried wrapping the body of the function in a 'begin', however when run it claims that 'begin' is not defined. I am using the Beginner Student language version as oppose to straight-up Racket. Any insight on a workaround?


Solution

  • The problem remains the same: in the language that's being used, we can't write more than one expression inside a function body, we can't use begin to pack more than one expression, and both let and lambda (which would have allowed us to create local bindings) are forbidden. That's a lot of restrictions, but we can get around using a helper function that calculates the price each time:

    (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)]))
    

    Alternatively: if price is used only once, simply in-line the expression that calculates it, there's no need to create a local variable or a helper function.