如何在scala中返回一个函数
如何返回 function Scala 中的副作用词法闭包1?
例如,我正在查看 Go 中的此代码示例
...
// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return b
}
}
...
println(f(), f(), f(), f(), f())
: 1 2 3 5 8
我不知道如何在 Scala 中编写相同的内容。
1.在Apocalisp评论后更正
How can I return a function side-effecting lexical closure1 in Scala?
For instance, I was looking at this code sample in Go:
...
// fib returns a function that returns
// successive Fibonacci numbers.
func fib() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
return b
}
}
...
println(f(), f(), f(), f(), f())
prints
1 2 3 5 8
And I can't figure out how to write the same in Scala.
1. Corrected after Apocalisp comment
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
稍微短一点,不需要退货。
Slightly shorter, you don't need the return.
嘎!可变变量?!
您可以返回一个获取第 n 个 fib 的文字函数,例如:
编辑:由于您要求“每次调用 f 时获取不同的值”的功能方式,因此您将这样做。这使用了 Scalaz 的
State
monad:值
f
是一个状态转换函数。给定一个流,它将返回其头部,并通过获取其尾部来“变异”侧面的流。请注意,f
完全忽略了fib
。下面是一个 REPL 会话,说明了其工作原理:显然,您得到的值取决于您调用
f
的次数。但这都是纯功能性的,因此是模块化和可组合的。例如,我们可以传递任何非空 Stream,而不仅仅是fib
。所以你看,你可以产生效果而没有副作用。
Gah! Mutable variables?!
You can return a literal function that gets the nth fib, for example:
EDIT: Since you asked for the functional way of "getting a different value each time you call f", here's how you would do that. This uses Scalaz's
State
monad:The value
f
is a state transition function. Given a stream, it will return its head, and "mutate" the stream on the side by taking its tail. Note thatf
is totally oblivious tofib
. Here's a REPL session illustrating how this works:Clearly, the value you get out depends on the number of times you call
f
. But this is all purely functional and therefore modular and composable. For example, we can pass any nonempty Stream, not justfib
.So you see, you can have effects without side-effects.
虽然我们正在分享与问题无关的斐波那契函数的酷实现,但这里有一个记忆版本:
它使用实现的记忆定点组合器作为此问题的答案:在 Scala 2.8 中,使用什么类型存储内存中的可变数据表?
顺便说一句,组合器的实现建议使用一种稍微更明确的技术来实现
function副作用词法闭包:While we're sharing cool implementations of the fibonacci function that are only tangentially related to the question, here's a memoized version:
It uses the memoizing fixed-point combinator implemented as an answer to this question: In Scala 2.8, what type to use to store an in-memory mutable data table?
Incidentally, the implementation of the combinator suggests a slightly more explicit technique for implementing your
functionside-effecting lexical closure:知道了!!经过一番尝试和错误:
测试:
Got it!! after some trial and error:
Testing:
使用元组时不需要临时变量:
但在现实生活中,您应该使用 Apocalisp 的解决方案。
You don't need a temp var when using a tuple:
But in real life you should use Apocalisp's solution.