functional programming - Accessing call stack depth in Scheme -


in order demonstrate effectiveness of tail recursion, way access depth of call stack dynamically in scheme.

is there way this? if not, there way in other major functional languages (ocaml, haskell, etc.)?

racket allows store values in call stack. can use keep track of depth. here how it:

#lang racket ;;; module holds tools keeping track of ;;; current depth. (module depth racket   (provide (rename-out [depth-app #%app])            current-depth)    (define (extract-current-continuation-marks key)     (continuation-mark-set->list (current-continuation-marks) key))    (define (current-depth)     (car (extract-current-continuation-marks 'depth)))    (define-syntax (depth-app stx)     (syntax-case stx ()       [(_depth-app proc args ...)        #'(let ([p  (with-continuation-mark 'depth (+ (current-depth) 1)                       proc)]                [as (with-continuation-mark 'depth (+ (current-depth) 1)                      (list args ...))])            (apply p as))])))  ;;; importing #%app depth module override ;;; standard application use depth-app keeps ;;; track of depth. (require 'depth)  (with-continuation-mark 'depth 0  ; set initial depth 0   (let ()     ;;; example:  foo tail recursive     (define (foo n)       (displayln (list 'foo n (current-depth)))       (if (< n 5)           (foo (+ n 1))           'done))      ;;; bar not tail recursive     (define (bar n)       (displayln (list 'bar n (current-depth)))       (if (< n 5)           (cons n (bar (+ n 1)))           '()))      ;;; call examples     (foo 0)     (bar 0))) 

the output is:

(foo 0 2) (foo 1 2) (foo 2 2) (foo 3 2) (foo 4 2) (foo 5 2) (bar 0 2) (bar 1 3) (bar 2 4) (bar 3 5) (bar 4 6) (bar 5 7) '(0 1 2 3 4) 

the output shows depth doesn't increase in foo , in bar.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -