Question

Apologies if the question title is a bit confusing. Maybe after you are through reading it, you can suggest me a better title.

As a part of a homework assignment for an online course, I wrote an iterative procedure in mit-scheme to display number from 1 to a given number.

The code below works fine:

(define (count2-iter num)
    (define (iter counter)
        (cond ((> counter num) #t)
              (else (display counter)
                (iter (+ counter 1)))))
    (iter 1))

The output:

1 ]=> (load "count2-iter.scm")

;Loading "count2-iter.scm"... done
;Value: count2-iter

1 ]=> (count2-iter 10)
12345678910
;Value: #t

Personally I do not like using cond for 2 branches only and I tried to use if for this.

(define (count2-iter1 num)
    (define (loop idx)
        (if (> idx num)
            #t
            ((display idx)
             (loop (+ idx 1)))))
    (loop 1))

The output:

1 ]=> (count2-iter1 5)
5
;The object #!unspecific is not applicable.
;To continue, call RESTART with an option number:
; (RESTART 2) => Specify a procedure to use in its place.
; (RESTART 1) => Return to read-eval-print level 1.

Why is this? Shouldn't #t be evaluated the same way it was used in cond? Would really appreciate an explanation as I am still new to Scheme.

Was it helpful?

Solution

Try this instead:

(define (count2-iter1 num)
  (define (loop idx)
    (if (> idx num)
        #t
        (begin ; notice the difference!
          (display idx)
          (loop (+ idx 1)))))
  (loop 1))

Here's why: when you use an if, there can be only one expression in the consequent part and one in the alternative part. If more than one expression is needed, we have to surround them with a (begin ...). You surrounded the expressions between (...), which is not ok, because parenthesis are used for function application (that's why the error message states that The object #!unspecific is not applicable).

On the other hand, a cond has an implicit begin for each of its clauses when a condition is met. Personally, I prefer to stick with using cond when I need more than one expression after a condition - it's less verbose.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top