我是dr.racket的初学者。我被要求编写一个函数来完成以下操作:编写一个函数"readnum“,它不会消耗任何东西,每次调用它,它都会生成定义列表的N个编号。
示例:
(定义一个(列表0 2-5 0))
readnum ->0(首次调用readnum )
重新开始->2(第二次命名为readnum )
重新开始--> -5 (第三次调用readnum )
您不必担心列表中有数字或没有数字可供阅读的情况。
Dr.racket是一种函数式语言,变异变量并使用它们作为计数器是非常不方便的,在这个问题中,我不允许定义其他全局函数和变量(虽然允许局部变量)。这是我的尝试,但似乎行不通:
(define counter -1)
(define lstofnum (list 5 10 15 20 32 3 2))
(define (read-num)
((begin(set! counter (+ 1 counter)))
(list-ref lstofnum counter)))我不仅定义了不允许的全局变量,而且输出也不太正确。
任何帮助都将不胜感激,谢谢!
发布于 2015-01-23 20:33:02
这里的诀窍是在实际定义函数之前声明一个局部变量,这样状态就在闭包中,我们可以根据需要更新它。
我们可以使用list-ref实现解决方案并保存当前索引,但不建议这样做。最好将列表和cdr存储到它的末尾,这就是我的意思:
(define lstofnum (list 0 2 -5 0))
(define readnum
(let ((lst lstofnum)) ; list defined outside will be hardcoded
(lambda () ; define no-args function
(if (null? lst) ; not required by problem, but still...
#f ; return #f when the list is finished
(let ((current (car lst))) ; save the current element
(set! lst (cdr lst)) ; update list
current))))) ; return current element它如预期的那样运作:
(readnum)
=> 0
(readnum)
=> 2
(readnum)
=> -5
(readnum)
=> 0
(readnum)
=> #fhttps://stackoverflow.com/questions/28118032
复制相似问题