为什么会出现在游戏2.0.2用于形成褶皱的方法? [英] Why is there a fold method for Form in Play 2.0.2?
问题描述
我指的是这样的:
的http://www.playframework.org/documentation/api/2.0.2/scala/index.html#play.api.data.Form
如果你寻找一个叫做折叠的方法,它显示了用于处理表格的方法。是否有一个为什么这种方法被称为折的原因吗?鉴于折已经具备了类似的对象列表中的意思,似乎这个名字很容易引起混淆。
If you search for a method called fold, it shows a method used for handling the form. Is there a reason why this method is called fold? Given that fold already has a meaning for list like objects, it seems that this name could easily cause confusion.
推荐答案
的折叠
在表格
是pretty接近折叠
在Scala的标准库中的为
类,它同样经常被用来捕捉过程的结果可能要么成功(在这种情况下,你有一个右
包含结果)或失败(在这种情况下,你有一个左
包含错误,或者吃剩的输入等)。所以,我会使用为
在这里举例。只是图片表格[T]
作为一种为[表格[T],T]
,如果必要。
The fold
on Form
is pretty close to the fold
on the Either
class in the Scala standard library, which is similarly often used to capture the outcome of a process that could either succeed (in which case you have a Right
containing the result) or fail (in which case you have a Left
containing an error, or maybe leftover input, etc.). So I'll use Either
as an example here. Just picture Form[T]
as a kind of Either[Form[T], T]
if necessary.
我们可以(很非正式的)想象列为有许多不同的形状的(空列表,一个长度,长度为二,等等的列表)和折叠
(或 foldLeft
,在下面的例子中)作为折叠正确类型的任何列表到一个类的话的方法,不管它的形状是:
We can (very informally) imagine lists as having lots of different "shapes" (empty lists, lists of length one, length two, etc.), and fold
(or foldLeft
, in the following example) as a method that collapses any list of the proper type to a single kind of thing, no matter what its shape is:
scala> def catInts(xs: List[Int]): String = xs.foldLeft("")(_ + _.toString)
catInts: (xs: List[Int])String
scala> catInts(List(1, 2, 3, 4))
res0: String = 1234
scala> catInts(Nil)
res1: String = ""
无论/表上折叠
同样,我们可以想像为
为具有两个形状(右键
和左
),其折叠
作为采取任何形状的为
并返回一个方法之类的话。假设我们有对于解析字符串为整数,并返回下面的方法的为
:
Fold on Either / Form
Similarly we can imagine Either
as having two shapes (Right
and Left
), and its fold
as a method that takes an Either
of either shape and returns a single kind of thing. Say we have the following method for parsing strings as integers and returning an Either
:
def parseInt(s: String): Either[String, Int] =
try Right(s.toInt) catch {
case _: NumberFormatException => Left(s)
}
和使用折叠
折叠为
下面的方法:
And the following method that uses fold
to collapse the Either
:
def toDefault(e: Either[String, Int]): Int = e.fold(_ => 42, identity)
,我们可以使用这样的:
Which we can use like this:
scala> toDefault(parseInt("AAARGH!!"))
res2: Int = 42
scala> toDefault(parseInt("123"))
res3: Int = 123
这是一切显然是非常IM pressionistic和手工波浪,但它可能会帮助给出了如何在不同的倍
方法基本上是相同的一个更直观的感觉之类的话。你可以看到我上面或的上catamorphisms的维基百科条目了解详细信息。
This is all obviously very impressionistic and hand-wavy, but it might help give a more intuitive sense of how the different fold
methods are fundamentally the same kind of thing. You can see the question I linked in a comment above or the Wikipedia entry on catamorphisms for more detail.
这篇关于为什么会出现在游戏2.0.2用于形成褶皱的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!