gpt4 book ai didi

javascript - 太多的递归方案javascript

转载 作者:行者123 更新时间:2023-11-30 18:07:10 25 4
gpt4 key购买 nike

我在 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

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

最佳答案

需要方案实现来优化尾调用,以便递归在常量空间中执行。最有可能的是,假设您的代码是尾递归的,基于 Javascript 的“解释器”不会进行该优化。 [实际上,考虑到优化可能会在编译期间完成,而不太可能在解释期间完成。]

关于javascript - 太多的递归方案javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15537996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com