Kestrel 函数式编程设计模式的附加价值是什么?(斯卡拉) [英] What is the added value of the kestrel functional programming Design Pattern? (Scala)
问题描述
我想知道为什么使用 Kestrel 处理代码的副作用部分如此有用.有没有人有经验?并且可以解释真正的动机以及它究竟是如何帮助的.
I'm wondering why is it so useful to put away the side effect part of a code using Kestrel. Does anyone has experience with it? and can explain the real motivation and how does it help exactly.
虽然我明白纯函数式编程是关于零副作用的,因此代码的调试和可预测性更好.但是,就 Kestrel 而言,我看不出这样做有什么帮助?
Although i understand that Pure functional programing is about zero-side effect and henceforth better debugging and predictability of the code. However in the case of Kestrel, I don't see how it really help to do that ?
最好的,
MM-
推荐答案
重点是要避免创建一个您可能不想放置的中间变量,或者避免必须为您想要的东西创建一个新块正在做路过.假设我们有 Ruby 中的 Kestrel:
The point is to avoid creating an intermediate variable that you probably don't want to have lying around, or to avoid having to create a new block for something you're doing in passing. Let's suppose we have the Kestrel as in Ruby:
implicit class RubyKestrel[A](val repr: A) extends AnyVal {
def tap[B](f: A => B) = { f(repr); repr }
}
现在假设我们有一些代码行:
Now let's suppose we have some line of code:
xs.map(_ + 7).filter(foo).take(n)
并且我们想在过滤器之后打印出调试消息.在没有 tap
的情况下,我们将该行重构为:
and we want to print out a debugging message after the filter. Without tap
we refactor that line to:
{
val temp = xs.map(_ + 7).filter(foo)
println(temp)
temp.take(n)
}
呃.现在假设我们有 tap
:
Ugh. Now suppose we have tap
:
xs.map(_ + 7).filter(foo).tap(println).take(n)
哇,好多了!
假设我们有一个包含 add 方法的堆栈,我们想在其他地方使用它之前向堆栈添加一些东西.
Let's suppose we have a stack that has an add method, and we want to add something to the stack before using it somewhere else.
def newStack = {
val stack = new Stack
stack add "whatever"
stack
}
呃.但是使用 tap
:
def newStack = (new Stack).tap(_ add "whatever")
非常方便——它真的只是让你把任何普通的副作用方法变成你可以链接调用的东西.而且由于链接调用通常是较低的样板文件,因此这通常是一个巨大的胜利.
Pretty handy--it really just lets you turn any normal side-effecting method into something that you can chain calls to. And since chained calls are often lower boilerplate, that's often a big win.
这篇关于Kestrel 函数式编程设计模式的附加价值是什么?(斯卡拉)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!