0

Here is the code I came out (to display all pairs of balanced parentheses with length n)

(define (combine-list l r)
(append l  (cons r '())))

;(combine-list '(1 2 3) '(4 4))

(define(bps n)
  (bps-iter '() (/ n 2) 0 0))


(define (bps-iter lst n open close) (;(display open) (display close) (display "\n")
  (cond ((eq? n close) (display lst)) 
        (else ((if (> open close)
                        (bps-iter (combine-list lst 1) n open (+ 1 close) ))
              (if (< open n)
                       (bps-iter (combine-list lst 0) n (+ open 1) close))) 
       )
        )))

(bps 4)

And it turned out as

application: not a procedure;
expected a procedure that can be applied to arguments
  given: #<void>
  arguments...: [none]

Is there any problem when it finished calling (eq? n close) and get back to 'else' to look for another set of parenthesis?

1 Answers1

0

Your problem is:

((if (> open close)
     (bps-iter (combine-list lst 1) n open (+ 1 close)))
 (if (< open n)
     (bps-iter (combine-list lst 0) n (+ open 1) close)))

This has this structure:

((if predicate
     consequence
     'undefined)
 (if predicate2
     consequence2
     'undefined))

And the result of the two if either is the result of bps-iter or some undefined value.. Lets say the two can be abbreviated if-exp1 and if-expr2, then you get:

(if-expr1 if-expr2)

From this it is safe to conclude that if the predicate1 is not true you will try to call undefined as if it was a function and in the case it is true bts-iter should at least return a function. Since noe of these are true it is destined to fail.

How to use if:

(if predicate
    consequence
    alternative) ; optional in R6RS, turns into undefined

These can be nested.

Sylwester
  • 47,942
  • 4
  • 47
  • 79
  • Is there a possible way that in r5rs, two if statement will both be processed if they both meet the predicate? If I try to nest them then it is not possible to trigger both of them. – Zhiwei Huang Dec 13 '17 at 23:16
  • @ZhiweiHuang `(begin expr1 ... exprn)` is like `{...}` in C languages. All but the last expression is for side effect only and the result of the form is the value of `exprn`. For expressions not needed to be top level nested `let` would do the same job. – Sylwester Dec 13 '17 at 23:46