CTM: Exercise 2-4

Posted by Urban Hafner Thu, 25 Aug 2005 10:06:28 GMT

The problem

The if and case statements. This exercise explores the relationship between the if statement and the case statement.

(a) Define the if statement in terms of the case statement. This shows that the conditional does not add any expressiveness over pattern matching. It could have been added as a linguistic abstraction.

(b) Define the case statement in terms of the if statement, using the operations Label, Arity, and '.' (feature selection).

This shows that the if statement is essentially a more primitive version of the case statement.

My solution

(a) What we are trying to emulate is the statement

*if* <x> *then* <s>1 *else* <s>2 *end*

As we are only covering the kernel language we can assume that is either true or false, so the if statement can easily be translated into:

*case* <x> *of* *true* *then* <s>1 *else* <s>2 *end*
(b) What we have to check is, that 1) the labels of and the are the same 2) that the both have the same arity and the field names are the same and 3) that the field values are the same.

  if {Label <x>}=={Label <pattern>} then
    if {Arity <x>}=={Arity <pattern>} then
      if <x>.first==<pattern>.first then
        if <x>.second=<pattern>.second then
          ...
          <s>1
        else <s>2 end
      else <s>2 end
    else <s>2 end
  else <s>2 end

If course this is not exactly right, because Arity returns a list which (I think) cannot be compared with ==, but the idea should be right.

Tags , ,

Comments are disabled