The tree is a linear list or non-linear list, such as:
'(1 2 3 4)
'((1 2) 3 4)
'((1 (2)) 3 (4))
All the trees above will yield leaves in order: 1 -> 2 -> 3 ->4. I know how to deal with a linear tree:
(define (treeg tree)
(lambda ()
(if (null? tree)
'()
(let ((e (car tree)))
(set! tree (cdr tree))
e))))
So, you can use like this:
(define gtr (treeg '(1 2 3 4)))
;now you can get a leaf per `gtr` call.
But when facing non-linear tree, the following code failed:
(define (treeg tree)
(lambda ()
(if (null? tree)
'()
(let ((e (car tree)))
(set! tree (cdr tree))
(if (pair? e)
((treeg e)) ;here just yield first leaf.
e)))))
I know there is a call/cc
solution, but is there a solution using closures?