Play框架表单“折叠”方法命名的基本原理 [英] Play Framework Form "fold" method naming rationale

查看:152
本文介绍了Play框架表单“折叠”方法命名的基本原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Play Framework(2.x) Form class 有一个名为 fold 的方法,它的用法表示为:

  anyForm.bindFromRequest()。fold(
f => redisplayForm(f),
t => handleValidFormSubmission(t)


我的问题是为什么Play开发人员称这种方法为fold?作为一个免责声明,我是Scala的新手,但是我没有看到它和Scala fold 操作之间的联系。唯一的相似之处在于它是一个更高阶的函数;但我没有看到任何正在发生的组合,也没有在其实现中将内部委托给任何Scala折叠函数。

解决方案

我不是FP专家,但我的理解是,一般来说, fold 会将一个类型的内容完全转换为另一种类型,这是针对递归原始类型的结构(如果适用)。您通常为每种原始类型的案例提供相同类型的结果。



List 最为人熟悉。我一直认为 fold 基本上是一个带有累加器的for循环,但是您也可以将它看作两种情况,一种用于 Nil 情况,一个用于缺点情况。因为实际类型 List 是递归的,所以它必须是它的 fold



Scala标准库在 Option 上定义了 fold ,签名 fold [B](ifEmpty:⇒B)(f:(A)⇒B):B 。在这种情况下,因为类型不是递归的,所以 fold 实际上就是两种情况下的两个函数。



您的情况与选项非常相似。该类型不是递归的,因此 fold 基本归结为将其状态的所有情况映射到一个输出类型。



<请注意, fold map flatMap 不同后两者保留原始类型,但改变其内容。


Play Framework's (2.x) Form class has a method called fold who's usage is indicated as:

anyForm.bindFromRequest().fold(
  f => redisplayForm(f),
  t => handleValidFormSubmission(t)
)

Essentially, the first function parameter is what gets executed on binding failure, and the 2nd on binding success. To me it seems similar to the 'success' and 'error' callbacks of jquery's ajax function.

My question is why did the Play developers call the method "fold"? As a disclaimer I am new to Scala, but I am failing to see the connection between this and the functional Scala fold operation. The only similarity is that it is a higher order function; but I don't see any combining that is taking place, nor does it delegate internally in its implementation to any of the Scala fold functions.

解决方案

I'm not an FP expert, but it's my understanding that a fold, generally speaking, transforms the contents of a type into another type entirely, respecting the recursive structure of the original type, if applicable. You typically provide a result of the same type for each case of the original type.

List is most familiar. I've always thought of fold as basically a for loop with an accumulator, but you could also look at it as two cases, one for the Nil case and one for the Cons case. Because the actual type List is recursive, so must be its fold.

The Scala standard library defines fold on Option as well, with the signature fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B. In this case, because the type is not recursive, the fold really is simply two functions for two cases.

Your case is pretty similar to Option. The type isn't recursive, so fold basically boils down to mapping all cases of its status to one output type.

Notice that fold differs from map and flatMap in that the latter two preserve the original type, but change its contents.

这篇关于Play框架表单“折叠”方法命名的基本原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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