问题描述
也许是 Scala 学习者的空闲思考,但是......在我的修补中,我写了以下内容:
Idle pondering from a Scala learner perhaps, but ... in my tinkerings I've written the following:
( n.child.size > 0 ) && ( n.child.filter( ! _.isInstanceOf[Text] ).size == 0 )
('n' 是一个 scala.xml.Node,但这并不重要.也不是特定的逻辑.)
('n' is a scala.xml.Node, but that's not important. Nor is the particular logic.)
两次调用 child() 不太好,所以我正要改变它:
Calling child() twice isn't so good, so I was about to change it:
val list = n.child
( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 )
但是考虑到我非常欣赏能够过滤()和映射()等而无需声明中间变量,我立即发现这很臭.它是如此......如此......如此Java-ish!:p
But given how much I've come to much appreciate being able to filter() and map() and such without needing to declare intermediate variables, I found this immediately smelly. It's so... so... so Java-ish! :p
唉,通过 SO 和 Google 以及 ScalaDocs(尤其是 Any 和 AnyRef)和 The Book 没有发现任何合适的内容.我希望可能是这样的:
Alas, digging through SO and Google and the ScalaDocs (especially Any and AnyRef) and The Book has turned up nothing appropriate. I was hoping perhaps for something like:
n.child{ list => ( list.size > 0 ) && ( list.filter( ! _.isInstanceOf[Text] ).size == 0 ) }
甚至
n.child.with{ list => ... }
这样的东西存在吗?还是我只是陷入了一种无常的狂热?
Does something like this exist? Or am I just getting caught up in a variable-less-ness fervour?
推荐答案
with"在 Scala 中当然是一个保留字,所以我们称它为let",来自 Lisp 和 Haskell 中类似的绑定形式.原来let"只是写函数应用程序的一种倒退方式.
"with" is, of course, a reserved word in Scala, so let's call it "let", from the similar binding form in Lisp and Haskell. Turns out "let" is just a backwards way of writing function application.
def let[A,B](param:A)(body: A=>B):B = body(param)
let(n.child){list=> ...}
如果绑定变量只使用一次,你当然可以使用匿名函数形式,但这违背了目的.
If the bound variable is used only once, you could of course use the anonymous function form, but that defeats the purpose.
这篇关于“与"等价于 Scala 的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!