Play Framework Form “fold” method naming rationale

半城伤御伤魂 提交于 2020-01-23 08:16:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/24132325/play-framework-form-fold-method-naming-rationale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!