太多的递归方案javascript

时间:2013-03-21 01:40:18

标签: javascript recursion scheme

我在javascript中使用了一个方案解释器

当我尝试这段代码时,我收到错误“太多的递归”:

;;;basic things
(define map 
  (lambda (f l) 
    (if (null? l) l 
        (cons (f (car l)) (map f (cdr l))))))

(define filter 
  (lambda (p l)
    (if (null? l) l 
        (if (p (car l))
            (cons (car l) (filter p (cdr l)))
            (filter p (cdr l))))))

(define accumulate 
  (lambda (op initial sequence)
    (if (null? sequence)
        initial
        (op (car sequence)
        (accumulate op initial (cdr sequence))))))

(define reduce 
  (lambda (op sequence)
    (accumulate op (car sequence) (cdr sequence))))

(define append 
  (lambda (l1 l2)
    (if (null? l2) l1
        (append (cons (car l2) l1) (cdr l2)))))

(define make-list 
  (lambda (n f l)
    (if (= n 0) l
        (make-list (- n 1) f (cons (f n) l)))))

(define make-list2-
  (lambda (f n1 n2 l)
    (if (> n1 n2) l
        (make-list2- f (+ n1 1) n2 (cons (f n1) l)))))
(define make-list2 (lambda (f n1 n2) (make-list2- f n1 n2 null)))
(define identity (lambda (x) x))
(define randomitem (lambda (l) (nth (ceil (* (random ) (length l))) l))) 
;;;

(define random0to3 (lambda () (floor (* 4 (random )))))

(define moverandom (lambda (this) (move this (random0to3 ))))

(define searchforcreature 
  (lambda (this cx cy)    ;search only for neighbor tiles
    (begin (define y (make-list2 identity (- cy 5) (+ cy 5)))
         (define L (map (lambda (x) (map (lambda (y2) (cons x y2)) y))
           (make-list2 identity (- cx 5) (+ cx 5))))
        (define L2 (reduce append L))
        (define listoftiles (map (lambda (x) (tile-from-pos (car x) (cdr x))) L2))
        (define listoftiles2 (filter identity listoftiles))    ;remove the falses you get from trying invalid positions
        (define listofcreatures (filter (lambda (x) (and (creature? x) (not (= x this)))) (map topthing listoftiles2)))
        ;(pairtostring listofcreatures)
        (if (null? listofcreatures)
            #f
            (car listofcreatures)))))

(define update 
  (lambda (this world) 
    (begin
      (define target (searchforcreature this (creature-x this) (creature-y this)))
      (begin (print target)
      (if target
          (attack this target)
          (moverandom this))))))

但在searchforcreatures函数中有10而不是5, 这意味着我创建了400个项目的列表,然后使用tile-from-pos函数映射它们 但是当我在drScheme中测试相同的函数时它运行正常,是因为javascript没有针对递归进行优化吗?

我可以测试上述代码的游戏: thesamesite / textarea.html

游戏的主要代码,在方案中: thesamesite / env0.sc

1 个答案:

答案 0 :(得分:2)

需要方案实现来优化尾调用,以便递归在恒定空间中执行。最有可能的是,假设您的代码是尾递归的,基于Javascript的解释器'没有做优化。 [实际上,可能是因为优化将在编译期间完成,而在解释期间则不太可能。]