I have a school task where I have to write a function 'check()' that takes a list as an argument. This list takes 3 elements. The lists first element should be an operator and the other 2 elements should be datatypes. An example of the function call can look like this:
(check '(+ int int))
Where it should LITERALLY say Int. There should not be any numbers involved. This function should then return the correct outputed datatype depending on what kind of datatypes you use in your operation. For example:
(check '(+ int int))
should return int.
It also says:
"Your program should recognize the operators
'+', '-', '*', '/', 'quotient', '<', '>', '=','and ,'or'
and the datatypes:
'int','bool' and 'real'
An example of a test run could look like this:
> (check '(+ int int))
int
> (check '(* int bool))
The operator '*' does not accept bools!
> (check '(= (< (+ int int) (quotient int int)) (> int int)))
bool
> (check '(* int (+ real int)))
The operator '+' must have operands of the same numerical type!
This task took me by surprise as I have never really made any custom datatypes in Scheme. Didn't even know it was possible. I am new to Scheme (and programming in general). I currently have no idea where to start or what to do! Do I need to define int,bool and real? Do I need to define the operators? If so...how? Can anybody help me? Show me where to start or what the process should look like...
Believe it or not, this question is not about custom data types; it's only a framing device, to get students to think about recursion.
Fundamentally, recursion is about breaking down a problem into smaller and smaller pieces, until you have the most basic pieces left. In the case of this type checking function, you're confronted with input like (= (< (+ int int) (quotient int int)) (> int int))
and have to reduce it to an output like bool
.
The way to break it down is to consider that big input like the above as the equivalent of (= A B)
, where A is (< (+ int int) (quotient int int))
, and B is (> int int)
.
Then you break A down into (< C D)
, where C is (+ int int)
and D is (quotient int int)
. Then you apply the rules as given in the question. In particular, the following rules apply:
(+ int int)
⇒ int
(quotient int int)
⇒ int
(< C D)
⇒ (< int int)
⇒ bool
(> int int)
⇒ bool
(= A B)
⇒ (= bool bool)
⇒ bool
See the steps in reducing the problem smaller and smaller until you get to the most basic pieces (int
, real
, bool
)? That's recursion in a nutshell.
I hope this helps you get started on solving the problem.