Hello,

> However, in Scheme, returning a value inside a loop is troublesome. I
> must first break the loop and then return the value. So what is the
> correct way of doing this?

Scheme does not really have loops. At least not in the sense you know it from 
procedural languages. `for-each` is naught but a `map` that does not collect 
the return values. `map` is a slightly more efficient implementation for

(define (map proc arg)
    (if (null? arg)
        '()
        (cons (proc (car arg)) (map proc (cdr arg)))))

`for-each` would rather be something like

(define (map proc arg)
    (if (not (null? arg))
        (begin
         (proc (car arg)
         (map proc (cdr arg))))))

You see in the Scheme paradigm you’d rather use recursion than loops. Scheme 
is optimized for tail-call recursion (that is if the final call in a function 
is a recursion Scheme will reuse the memory allocated).

In this Scheme paradigm doing something like nested scoping is actually quite 
nice. Instead of relying on breaks you’d recursively call the function until 
you get a match:

(define (hash-tree-get tree values default)
    (if (null? values)
        ; No keys left, so we return the whole result
        tree
        ; Scope first key
        (let ((val (hash-ref tree (car values))))
          (if val
              ; Key was found, continue scoping
              (hash-tree-get val (cdr values))
              ; Key was not found, return default
              default))))

Or alternatively like this:

(define (hash-tree-get tree values default)
    (if (null? values)
        ; No keys left, so we return the whole result
        tree
        ; Scope first key
        (let ((val (hash-ref tree (car values) default)))
          (if (hash-table? val)
              ; Key was found, continue scoping
              (hash-tree-get val (cdr values))
              ; Key was not found, return default
              val))))

Cheers,
Valentin

Attachment: signature.asc
Description: This is a digitally signed message part.

Reply via email to