问题描述
我指的是:
http://www.playframework.org/documentation/api/2.0.2/scala/index.html#play.api.data.Form
如果您搜索名为 fold 的方法,它会显示用于处理表单的方法.这种方法被称为折叠有什么原因吗?鉴于 fold 已经有 list like objects 的含义,这个名字似乎很容易引起混淆.
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.
推荐答案
Form
上的 fold
与表单上的 fold
非常接近Scala 标准库中的 Either
类,它同样经常用于捕获可能成功的过程的结果(在这种情况下,您有一个包含结果的 Right
)或失败(在这种情况下,您有一个 Left
包含错误,或者可能是剩余的输入等).因此,我将在这里使用 Either
作为示例.如有必要,只需将 Form[T]
想象成一种 Either[Form[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.
我们可以(非常非正式地)将列表想象成具有许多不同的形状"(空列表、长度为一的列表、长度为二的列表等),并且 fold
(或 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 = ""
在任一/表单上折叠
同样我们可以把Either
想象成有两个形状(Right
和Left
),它的fold
为一种方法,它采用任一形状的 Either
并返回一种事物.假设我们有以下方法将字符串解析为整数并返回 Either
:
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)
}
以及以下使用fold
折叠Either
的方法:
And the following method that uses fold
to collapse the Either
:
def toDefault(e: Either[String, Int]): Int = e.fold(_ => 42, identity)
我们可以这样使用:
scala> toDefault(parseInt("AAARGH!!"))
res2: Int = 42
scala> toDefault(parseInt("123"))
res3: Int = 123
这显然是非常印象派和手工波浪式的,但它可能有助于更直观地了解不同的 fold
方法如何从根本上说是同一种东西.你可以看到我在上面评论中链接的问题或有关 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.
这篇关于为什么 Play 2.0.2 中有 Form 的 fold 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!