Game form form "bend" naming method

Play Framework (2.x) The form class has a method called fold , the use of which is indicated as:

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

In fact, the first parameter of the function is what happens when the binding fails, and the second by the success of the binding. For me, this is similar to the “successful” and “erroneous” jquery ajax callbacks.

My question is: why did the Play developers name the "fold" method? As a disclaimer, I am new to Scala, but I do not see the connection between this and the functional Scala fold operation. The only similarity is that it is a function of a higher order; but I don’t see any combination that takes place, and it does not integrate any of the Scala fold functions inside its implementation.

+4
source share
1 answer

I'm not an FP expert, but I understand that, generally speaking, completely converts the contents of a type to another type, given the recursive structure of the original type, if applicable. Usually you get the result of one type for each case of the original type.

List most famous. I always thought of fold as in the main for loop with the battery, but you can also consider it as two cases: one for the Nil case and one for the Cons case. Since the actual type of List is recursive, it should be fold .

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

Your case is very similar to Option . A type is not recursive, so fold basically boils down to mapping all cases of its state to a single type of output.

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

+1
source

Source: https://habr.com/ru/post/1204928/


All Articles