Concrete Abstractions: Chapter 10

Exercise 10.2: Even when a category is directly testable by Scheme, using EBNF to express it at a more primitive level can help you appreciate the expressive power of EBNF. In this exercise you will use EBNF to describe certain kinds of numbers—a small subset of those allowed by Scheme.
a. Write a production for <unsigned-integer>. You can use the productions for <digit> given above.
b. Next write productions for <integer>; an <integer> may start with a – sign, a + sign, or neither.
c. Finally, write productions for <real-number>, which are (possibly) signed numbers that may have a decimal point. Note that if the real number has a decimal point, there must be at least one digit to the left or to the right (or both) of the decimal point. Thus, -43., .43, 43, 43.21, and 43.0 are all valid real numbers.

Solution: a. <unsigned integer> -> <digit>+
b. <integer> -> -<unsigned integer> | +<unsigned integer> | <unsigned integer>
c. <real-number> -> <integer>. | <integer>.<unsigned integer>* | .<unsigned integer>+ | <integer>

Exercise 10.3: In Section 8.3 we considered expression trees for simple arithmetic expressions. All such expressions are either numbers or lists having an operator (one of +, -, *, or /) and two operands. Actually, there are three important variants, depending on where the operator occurs: in the first position (prefix or Scheme notation), the second position (infix or standard notation), or the third position (postfix, also known as Reverse Polish notation, or RPN). Let’s consider how such expressions can be specified using EBNF.
a. Write productions for <arithmetic-prefix-expression>.

b. Write productions for <arithmetic-infix-expression>.

c. Write productions for <arithmetic-postfix-expression>.

d. As noted in Section 8.3, a postorder traversal of an expression tree re-
sults in a list of the nodes that is identical to the language specified by <arithmetic-postfix-expression>, except that subexpressions are not parenthesized. Revise the productions for <arithmetic-postfix-expression> so that subexpressions are not parenthesized. (The overall top-level expression needn’t be parenthesized either.)

Solution:  <arithmetic-expression> -> + | – | * | /
a. <arithmetic-prefix-expression> -> (<arithmetic-expression> <real-number> <real-number>)
b. <aritmethic-infix-expression> -> (<real-number> <arithmetic-expression> <real-number>)
c. <arithmetic-postfix-expression> -> (<real-number> <real-number> <arithmetic-expression>)

Exercise 10.4: Let’s consider two possible additions to our Micro-Scheme grammar involving regular Scheme expressions.
a. Write a production for let expressions. Remember that let expressions allow zero or more bindings (i.e., parenthesized name/expression pairs), and the body of the let contains one or more expressions. You should define a separate syntactic category for <binding>.
b. Write productions for cond expressions. Remember that cond expressions allow one or more branches, the last of which may be an else, and each branch has one or more expressions following the test condition.

Solution: a. <binding> –> (let ((<name> <expression>)*) <expression>+>
b.
<condition> –> (cond ((<expression>+ <expression>))+ (else <expression>+ )*)

Exercise 10.6:

Solution: a. (if 3 1 5) is a <conditional>. Let’s check if 3, 1, and 5 are <expression>s. 3, 1 and 5  are <number>s which are <literal>s which are <constant>s which are <expression>s. So that’s valid.
b. (lambda x (+ x 2)) that isn’t valid because a <abstraction> needs parenthisis after lambda.
c. (((a ((b))) c)) that looks like an <application> let’s check if ((a ((b))) c) is an <expression>. Because an <application> is an <expression> we have to check if <em>(a ((b)))</em> and <em>c</em> is an <expression>. c is an <name> and therefore an <expression>. <em>(a ((b)))</em> is an <application> which have to consists of one or more expressions. So there’s <em>a ((b))</em> left to check. a is an <expression>. ((b)) is an <application> of an <application> of a <name> which is an <expression>. So that’s valid.
d. (lambda (lambda) 3). We have to check if lambda ist a <name> which is false. Not valid.
e. (lambda () lambda). We have to check if lambda is an <expression> which it isn’t.
f. (lambda (x) (if (> x 0) x (- x) 0)). Let’s check if <em>if</em> is an <conditional>. It isn’t because it has more than three <expression>s in its body.
g. (lambda () x). This is valid if x is an <expression>. A <name> is an <expression>, so this is valid.
h. (lambda () ). Not valid, because there’s no <expression> in the body.
i. (/). Not valid, because it needs at least two <arithmetic-expression>s in the body.
j. (#t #f). This is an <application> of two expressions. Are #f and #t <expression>s?  They aren’t definied, so this is not valid.

Exercise 10.31: Use EBNF to write a grammar for the language of all strings of one or more digits that simultaneously meet both of the following requirements:
a. The digits alternate between even and odd, starting with either.

b. The string of digits is the same backward as forward (i.e., is palindromic).

Solution:

<even> -> 0 | 2 | 4 | 6 | 8
<odd>  -> 1 | 3 | 5 | 7 | 9
<palindrome-even> -> 0<palindrome-odd>0 | 2<palindrome-odd>2 | 4<palindrome-odd>4 | 6<palindrome-odd>6 |
                     8<palindrome-odd>8 | <even>
<palindrome-odd> ->  1<palindrome-even>1 | 3<palindrome-even>3 | 5<palindrome-even>5 | 7<palindrome-even>7 | 
                     9<palindrome-even>9 | <odd>
<legal> -> <palindrome-even> | <palindrome-odd>

 

SPOJ: 8132. Street Trees

A group of trees is planted along a straight line.

KOI is planning to plant more trees so that the distance between two adjacent trees is equal for all trees.

For simplicity, each tree can only be planted on an integer coordinate.

Problem: Sphere Online Judge (SPOJ) – Problem STREETR

Solution:
To illustrate this problem I drew this small graphic:

The large trees are given and we have to find the small ones. You can see pretty fast that the maximum difference between trees is the minimum difference between already planted trees. But we’re not only looking for one arbitrary solution (which would be zero difference), we’re looking for the greatest difference or more generally the Greatest common divisor.

 Python |  copy code |? 
01
def gcd(a, b):
02
    if b == 0:
03
        return a
04
    else:
05
        return gcd(b, a % b)
06
 
07
 
08
def gcdList(lst):
09
    myGcd = gcd(lst[0], lst[1])
10
    for c in lst[1:]:
11
        myGcd = gcd(myGcd, c)
12
 
13
    return myGcd
14
 
15
N = int(raw_input())
16
diff = []
17
lastTree = int(raw_input())
18
for i in xrange(1, N):
19
    newTree = int(raw_input())
20
    diff.append(newTree - lastTree)
21
    lastTree = newTree
22
 
23
myGcd = gcdList(diff)
24
 
25
trees = map(lambda x: (x / myGcd) - 1, diff)
26
print sum(trees)
27

Concrete Abstractions: Chapter 9

Exercise 9.2: The sequences we just described are restricted to consecutive increasing sequences of integers (more precisely, to increasing arithmetic sequences where consecutive elements differ by 1). We can easily imagine similar but more general sequences such as <6, 4, 3, 2> or <5, 5.1, 5.2, 5.3, 5.4, 5.5>—in other words, general arithmetic sequences of a given length, starting value, and increment (with decreasing sequences having a negative increment value).
a. Write a procedure sequence-with-from-by that takes as arguments a length, a starting value, and an increment and returns the corresponding arithmetic sequence. Thus, (sequence-with-from-by 5 6 -1) would return the first and (sequence-with-from-by 6 5 .1) would return the second of the two pre- ceding sequences. Remember that sequences are represented as procedures, so your new sequence constructor will need to produce a procedural result.
b. The procedure sequence-from-to can now be rewritten as a simple call to sequence-with-from-by. The original sequence-from-to procedure made an empty sequence if its first argument was greater than its second, but you should make the new version so that you can get both increasing and de- creasing sequences of consecutive integers. Thus, (sequence-from-to 3 8) should return <3, 4, 5, 6, 7, 8>, whereas (sequence-from-to 5 1) should return <5, 4, 3, 2, 1>.
c. Write a procedure sequence-from-to-with that takes a starting value, an ending value, and a length and returns the corresponding arithmetic sequence. For example, (sequence-from-to-with 5 11 4) should return <5, 7, 9, 11>.

Solution:

 Scheme |  copy code |? 
01
; a.
02
(define sequence-with-from-by
03
  (lambda (start len inc)
04
    (lambda (op)
05
      (cond ((equal? op 'empty-sequence?)
06
            (= len 0))
07
            ((equal? op 'head)
08
             start)
09
            ((equal? op 'tail)
10
             (sequence-with-from-by (+ start inc) (- len 1) inc))
11
            ((equal? op 'sequence-length)
12
             len)
13
            (else
14
             (error "illegal operation" op))))))
15
 
16
; b.
17
(define sequence-from-to
18
  (lambda (a b)
19
    (if (< a b)
20
        (sequence-with-from-by a (+ (- b a) 1)  1)
21
        (sequence-with-from-by a (+ (- a b) 1) (- 1)))))
22
 
23
; c.
24
(define sequence-from-to-with
25
  (lambda (start end len)
26
    (sequence-with-from-by start len (/ (+ (- end start) 2) len))))

Exercise 9.6: Write the sequence constructor sequence-map, that outwardly acts like the list procedure map. However unlike map, which applies the procedural argument to all the list elements, sequence-map should not apply the procedural argument at all yet. Instead, when an element of the resulting sequence (such as its head) is accessed, that is when the procedural argument should be applied.

Solution:

 Scheme |  copy code |? 
01
(define sequence-map
02
  (lambda (sequence f)
03
      (lambda (op)
04
        (cond
05
         ((equal? op 'empty-sequence?)
06
          (empty-sequence? sequence)) 
07
         ((equal? op 'head)
08
          (f (head sequence))) 
09
         ((equal? op 'tail)
10
          (sequence-map (tail sequence) f)) 
11
         ((equal? op 'sequence-length)
12
          new-length)
13
         ((equal? op 'sequence-ref) 
14
          (lambda (n)
15
           (if (= n 0) 
16
            head
17
            (sequence-ref tail (- n 1))))) 
18
         (else (error "illegal sequence operation" op))))))

Exercise 9.: One way we can represent a set is as a predicate (i.e., a procedure that returns true or false). The idea is that to test whether a particular item is in the set, we pass it to the procedure, which provides the answer. For example, using this representation, the built-in procedure number? could be used to represent the (infinite) set of all numbers.
a. Implement element-of-set? for this representation. It takes two arguments, an element and a set, and returns true or false depending on whether the element is in the set or not.
b. Implement add-to-set for this representation. It takes two arguments, an ele- ment and a set, and returns a new set that contains the specified element as well as everything the specified set contained. Hint: Remember that a set is represented as a procedure.
c. Implement union-set for this representation. It takes two arguments—two sets— and returns a new set that contains anything that either of the provided sets contains.

Solution:

 Scheme |  copy code |? 
01
; a
02
(define element-of-set?
03
  (lambda (element set)
04
    (set element)))
05
 
06
; b.
07
(define add-to-set
08
  (lambda (element set)
09
    (lambda (ele)
10
      (if (equal? ele element)
11
          #t
12
          (set ele)))))
13
 
14
; c.
15
(define union-set
16
  (lambda (set1 set2)
17
    (lambda (ele)
18
      (or (set1 ele) (set2 ele)))))
19

Exercise 9.: Assume that infinity has been defined as a special number that is greater than all normal (finite) numbers and that when added to any finite number or to itself, it yields itself. Now there is no reason why sequences need to be of finite length. Write a constructor for some interesting kind of infinite sequence.

Solution:

 Scheme |  copy code |? 
01
; Ex 9.22
02
(define sequence-from-to-inf
03
  (lambda (from)
04
    (lambda (op)
05
      (cond ((equal? op 'head)
06
             from)
07
            ((equal? op 'tail)
08
             (sequence-from-to-inf (+ 1 from)))
09
            ((equal? op 'sequence-length)
10
             +inf.0)
11
            (else
12
             (error "operation not found" op))))))
13
 
14
 
15
 
16
; Interesting application
17
(define display-even-sequence
18
  (lambda (seq)
19
    (if (even? (head seq))
20
        (display (head seq))
21
        (display " "))
22
    (display-even-sequence (tail seq))))
23
 
24
 
25
(define display-f-sequence
26
  (lambda (seq f)
27
    (display (f (head seq)))
28
    (display " ")
29
    (display-f-sequence (tail seq) f)))