scala - why use foldLeft instead of procedural version? -


Then it has been said that instead of procedural code:

  def extension ( Exchange: string, substitution: traversable [(string, string)]: string = {var result = XP (old, newer) & lt; You can write the following functional code:  
  def extension (Expand: - Replacement) Results = result. Rale (old S, new) result}   

String, Replacement: Traversable [(String, String)]: String = {Replacement. Folded Lift (XP) {Case (Results, (Old, New))> & gt; the resulting. (Old S, New)}} I almost certainly will write the first version because the cedars familiar to any procedural or functional styles can easily read and understand, while only the codec is familiar, the functional style can easily read and understand the second version. is.

But separating readability for time, is there any such thing that makes a better choice than the mistake procedural version? I thought it would be more efficient, but it has been found that in fact it is just the above procedural code, is it just a style, or is there a good reason to use one version or the other?

Edit: To be clear, I'm not asking about the other function, just type the goondle foreach , I'm totally happy using the map , filter , etc., which are all ready to understand the map well.

Answer: Here are two good answers (even more given) though I can only accept one:

  • foldLeft because there are additional customizations, such as using a while loop that will be faster than one for the loop.
  • Use fold , if it is occasionally added to the regular collection, because it parrots the transition to parallel the compilation.

    This is less and obvious - yes, you need to know that to understand it What's the one time, but when you're programming in a language that is 50% functional, you should know these basic building blocks anyway One-fold actually processes the code (repeatedly to apply an operation), but it has been given a name and it has been normalized. And when it's just a small wheel that you're changing again, but it's still a rebuild wheel.

    And if the implementation of the gal will ever get some special reactions - say, additional customization - you can get countless ways without getting updates for free.

Comments