kestrel功能编程设计模式的附加值是多少? (斯卡拉) [英] What is the added value of the kestrel functional programming Design Pattern? (Scala)

查看:92
本文介绍了kestrel功能编程设计模式的附加值是多少? (斯卡拉)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么使用Kestrel来放弃代码的副作用部分是非常有用的。有谁有经验吗?并且可以解释真正的动机,它如何有助于确切地。



虽然我明白Pure功能编程关于零副作用,从而更好地调试代码和可预测性。不过在凯斯特勒的情况下,我看不出有什么帮助吗?



最佳



MM -

解决方案

重点是为了避免创建一个中间变量,你可能不想说谎,或者避免为您正在做的事情创建一个新的块。我们假设我们在Ruby中有Kestrel:

 隐式类RubyKestrel [A](val repr:A)扩展AnyVal {
def tap [B](f:A => B)= {f(repr); repr}
}

现在我们假设我们有一行代码:

  xs.map(_ + 7).filter(foo).take(n)
/ pre>

,我们想在过滤器之后打印出一个调试消息。没有点击我们将该行重构为:

  {
val temp = xs.map(_ + 7).filter(foo)
println(temp)
temp.take(n)
}

现在假设我们有点击

  xs.map(_ + 7 ).filter(foo).tap(println).take(n)



假设我们有一个堆栈,它有一个add方法,我们希望在堆栈之前添加一些东西,然后再使用它。

  def newStack = {
val stack = new Stack
stack addwhatever
stack
}

呃。但是使用点击

  def newStack =(new Stack).tap (_添加任何)

相当方便 - 它只是让你转动任何正常的边 - 实现方法转化为可以链接调用的东西。而且由于链接电话通常是较低的样板,这通常是一个很大的胜利。


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.

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 ?

Best,

MM-

解决方案

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)

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)
}

Ugh. Now suppose we have tap:

xs.map(_ + 7).filter(foo).tap(println).take(n)

Whew, way better!

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
}

Ugh. But with 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆