是否可以在方案中制作切换功能?
在 ruby 中,您可以创建一个简单的切换函数,如下所示:
@switch = false
def toggle
@switch = !@switch
end
toggle # => true
toggle # => false
toggle # => true
我想知道是否可以在方案中执行此操作。我能得到的最接近的是:
(define a #f)
(define (toggle a)
(cond ((eq? a #t) #f)
(else #t)))
(define a (toggle a))
a # => #t
(define a (toggle a))
a # => #f
(define a (toggle a))
a # => #t
谢谢。
In ruby you can create a simple toggle function like so:
@switch = false
def toggle
@switch = !@switch
end
toggle # => true
toggle # => false
toggle # => true
I am wondering if it is possible to do it in scheme. The closest I can get is:
(define a #f)
(define (toggle a)
(cond ((eq? a #t) #f)
(else #t)))
(define a (toggle a))
a # => #t
(define a (toggle a))
a # => #f
(define a (toggle a))
a # => #t
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你愿意,你可以用同样的方式做:
这是作业吗?
You can do it the same way if you like:
Is this homework?
我会写这样的东西:
可以这样调用:
一点解释:外部 lambda 是一个函数,它采用初始状态并返回另一个函数,该函数在每次调用时来回翻转该状态。请注意,外部函数将通过最后一行的
#f
立即调用;然后 switch 被定义为该调用的结果,内部函数在闭包中捕获state
。您还可以编写如下内容:
make-switch
将我们之前的内容包装在另一个函数中。现在我们拥有的是一个制造开关的工厂,每个开关都有自己的内部状态。所以我们可以这样写:并看到每个开关都是独立的:
类似地,您可以参数化
make-switch
来设置开关的初始状态,以及打开和打开。希望这有帮助。
I would write something like this:
Which can be invoked like this:
A little explanation: the outer lambda is a function that takes an initial state and returns another function that flips that state back and forth upon each invocation. Note that the outer function is being invoked immediately with the
#f
on the last line; switch is then defined as the result of this invocation, the inner function capturingstate
in a closure.You could also write something like this:
make-switch
takes what we had before and wraps it in yet another function. Now what we have is a factory for making switches, each with their own internal state. So we can write something like this:And see that each switch is independent of the other:
Similarly you could parameterize
make-switch
to set the initial state of the switch, and on and on.Hope this helps.