Talk:Functional programming: Difference between revisions

Content deleted Content added
Line 150:
::Thanks. So b=2*a is ok, but a=2*a is not? I can see that that is more robust in general, if a tad inconvenient for incrementing indices. [[User:Greglocock|Greglocock]] ([[User talk:Greglocock|talk]]) 00:31, 25 April 2017 (UTC)
::: Yes, that's pretty much the essence; destructive updates to named variables are not allowed. The typical way of "incrementing indices" is passing the increased value to a recursive call; functional programming depends heavily on [[recursion]]. [[User:Diego Moya|Diego]] ([[User talk:Diego Moya|talk]]) 06:16, 25 April 2017 (UTC)
:::{{ping|Greglocock}} rand() will produce different results each time. scanner.nextInt() can produce new results each time. With a pure function, a compiler could theoretically decide that a result isn't used so the call is unneeded, or that a result is used a lot and it can be cached. A skipped call to rand() or scanner.nextInt() will affect the results of a program, while a skipped call to fibonacci(n) should not.
:::Most uses for incrementing indices are made unnecessary in functional programming languages. You would typically use a higher-order function like [[map (higher-order function)|map]], which roughly corresponds to the head of a for-loop, and give it another function, which roughly corresponds to the body of a for-loop. Many other languages have support for these concepts. C++'s <algorithm> library, Java's Stream interface, and Javascript's Array methods all have some kind of map/filter/reduce equivalent, which take a sequence and a function and return a transformed sequence or an aggregate value.
:::It is theoretically possible to allow updates to named variables within the body of a function, as long as the variables are local. The [[D programming language]] allows such updates in its pure functions.[https://dlang.org/spec/function.html#pure-functions] --[[Special:Contributions/96.232.200.75|96.232.200.75]] ([[User talk:96.232.200.75|talk]]) 20:20, 13 June 2017 (UTC)