Reputation: 211
I am using an online textbook to learn the Scheme programming language. I am having trouble understanding the solution to an exercise in the textbook (Exercise 2.3.1. at this page). The Exercise is as follows:
Utopia's tax accountants always use programs that compute income taxes even though the tax rate is a solid, never-changing 15%. Define the program tax, which determines the tax on the gross pay.
Also define netpay. The program determines the net pay of an employee from the number of hours worked. Assume an hourly rate of $12.
I made several attempts to complete it before resorting to the solution offered in the textbook (found here). The solution is as follows:
;; computes the tax
(define (tax w)
(* 0.15 w))
;; computes the net pay
(define (netpay h)
(- (wage h)
(tax (wage h))))
;; computes the wage for a given number of hours
(define (wage h)
(* h 12))
;; EXAMPLES TURNED INTO TESTS
(tax 100) ;; should be 15
(wage 2) ;; should be 24
(netpay 40) ;; should be 408
This is the part of the code that has me confused:
(define (netpay h)
(- (wage h)
(tax (wage h))))
I do not understand why this expression works. I was expecting to see a mathematical operator before wage
in (wage h)
and before tax
and wage
in (tax (wage h))
. The textbook doesn't mention this anomaly prior to this exercise. All previous examples look like (* num1 num2)
. Can someone clear my confusion? Thank You.
Upvotes: 2
Views: 101
Reputation: 43852
Indeed, there is a mathematical operator being used in those expressions, subtraction. The netpay
function could also be written out like this:
(define (netpay h)
(- (wage h) (tax (wage h))))
Is that more clear? In Scheme, whitespace is insignificant, which means that multiple spaces are equivalent to a single space, and linebreaks are equivalent to spaces. Basically, the amount of whitespace doesn't matter; it just serves as a generic seperator.
Scheme's prefix notation can sometimes be confusing before you get used to it. However, the basic idea is that all expressions are of the following form:
(f x ...)
This is equivalent to function application, also called "calling a function". In a C-like language, the syntax would likely look like this, instead:
f(x, ...)
The mathematical operators are just regular functions, so they share the same syntax. So, (+ 1 2)
is 3 and (* (+ 1 2) 3)
is 9 (see how they can be nested).
So, then, what does this expression do?
(- (wage h) (tax (wage h)))
It subtracts (tax (wage h))
from (wage h)
. In C-like syntax, this whole expression would look like this, instead:
wage(h) - tax(wage(h))
Upvotes: 2