Petr Kubelka
Petr Kubelka

Reputation: 25

Terminate program early and return list

I have a recursive code and need to terminate it when condition is fullfilled. I am capable of display the list when the condition, but then there are another calls on stack that I don't need to process that doesn't let me to return the list.

Upvotes: 0

Views: 65

Answers (2)

soegaard
soegaard

Reputation: 31145

A variation of Sylwester's solution:

(define (example n)
  (call-with-current-continuation
   (lambda (return)
     (let loop ([n 0])
       (if (= n 5) ; done
           (return 'the-result)
           (loop (+ n 1)))))))

(example 10)

Using the continuation in this way allows one to use an escape continuation instead of a full continuation with call/ec (if your implementation has escape continuations).

Upvotes: 1

Sylwester
Sylwester

Reputation: 48765

The best way to do it is by using an accumulator. Aborting is then just not recursing.

(define (copy-unless-contains-5 lst)
  (define (helper lst acc)
    (cond
      ((null? lst) (reverse acc))
      ((equal? (car lst) 5) #f) 
      (else (helper (cdr lst) (cons (car lst) acc)))))
  (helper lst '()))

If you are recursing with a continuation and that is the optimum way of doing it, then call-with-current-continuation can give you a way to abort waiting continuations and choose what to return.

(define (copy-unless-contains-5 lst)
  (call-with-current-continuation
   (lambda (abort)
     (define (helper lst)
       (cond
         ((null? lst) '())
         ((equal? (car lst) 5) (abort #f)) 
         (else (cons (car lst) (helper (cdr lst))))))
     (helper lst))))

Needless to say this last version is overly complicated. Both work the same:

(copy-unless-contains-5 '(1 2 3 4))   ; ==> (1 2 3 4)
(copy-unless-contains-5 '(1 2 5 3 4)) ; ==> #f

Upvotes: 1

Related Questions