26 septembrie 2014

Probleme în Scheme: Bintree

Credeam că nu mă voi mai întâlni niciodată cu limbajul Scheme.... dar se pare că m-am înșelat.
Așadar, acest exercițiu (și mai multe exemple în curând):

A Bintree is defined using the following grammar:
Bintree ::= Int
::= ( Symbol Bintree Bintree )
where Int and Symbol are non-terminals representing an integer and a symbol, respectively.
1) Write the following Scheme procedures. These are constructors for Bintree structures.
interior-node : Symbol x Bintree x Bintree -> Bintree
leaf: Integer -> Bintree
A Bintree is constructed using these two constructor. As for example:
(interior-node 'a (interior-node 'b (leaf 10) (leaf 20)) (leaf 30)) 
generates the Bintree '(a (b 10 20) 30)
2. Write the following Scheme procedures. These are observers for Bintree structures.
interior-node?: Bintree -> Boolean
leaf?: Bintree -> Boolean
interior-node->left : Bintree -> Bintree
interior-node->right: Bintree -> Bintree
interior-node->name: Bintree -> Symbol
leaf->value: Bintree -> Int
The first two are predicates: 
  • " interior-node?" tests whether its argument is an interior node constructed using the procedure "interior-node".
  • "leaf?" tests whether its argument is a leaf node, constructed using the procedure "leaf"
The remaining procedures extract elements from the Bintree structure.
  • "interior-node->left" and "interior-node->right" return the left and right nodes of an interior node. They produce errors if the input is not an interior-node.
  • "interior-node->name" returns the 'symbol' used to construct an interior node, and generates error if any other type of node is given.
  • "leaf->value" returns the integer value used to construct the leaf node. It returns error otherwise.
3) Write a procedure "number-leaves" that takes as input a Bintree and also returns a Bintree. The Bintree it returns is identical to its input, except that in the leaf nodes the value is replaced by a number representing the order of the leaf, from left to right (starting with zero).
number-leaves: Bintree -> Bintree
Example:
(number-leaves (interior-node 'a (interior-node 'b (leaf 55) (leaf 77)) (leaf 11))
will produce a bintree equivalent to the following (interior-node 'a (interior-node 'b (leaf 0) (leaf 1)) (leaf 2))
Soluția mea AICI
fișierul de test AICI 

Niciun comentariu: