The Many Faces of D - slides
Walter Bright
newshound2 at digitalmars.com
Sun Oct 3 12:43:07 PDT 2010
Russel Winder wrote:
> On Sun, 2010-10-03 at 09:59 -0400, bearophile wrote:
>> Page 20: is that functional? It even contains a mutable "sum" value.
>> It may be seen as kind-of-functional. A more functional style is to
>> use a reduce (fold) there, from std.algorithm.
>
> I agree this is a weird sort of an example of "functional".
> sum_of_squares as a function has no external side-effects (though
> clearly the iteration has a side effect internally) and is referentially
> transparent. So as a thing that can be used as a "functional
> programming" function it is fine, its implementation is though very much
> imperative programming -- at its worst ;-)
>
> Given an imperative language with no tail recursion capability then one
> has to declare a non-functional floor even when doing functional style
> programming. In effect the execution graph has to be allowed to have
> leaqf nodes that are implemented imperatively.
>
> Coming from a Pythonic realization of these ideas, list comprehensions
> seems to be the best way out of this sort of thing, so instead of:
>
> def sumOfSquares ( sequence ) :
> sum = 0.0
> for item in sequence :
> sum += item * item
> return sum
>
> it is better to write:
>
> def sumOfSquares ( sequence ) :
> return sum ( [ item * item for item in sequence ] )
>
> So the question is whether there is an idiomatic D version of this.
This is quite deliberate on my part, and I'm glad it piqued your interest. D's
support for functional programming is NOT about all data being immutable. It is
about being able to draw a circle around a block of code (i.e. a function) and
saying that "THIS block of code has no side effects." If it modifies variables
internally that is of no import if those modifications are not visible outside
of that block.
This is, in my not so humble opinion, of great value in that one does NOT have
to rethink one's approach to coding in order to gain the advantages of
functional programming. I.e. one can write a normal loop such as the sum one,
rather than trying to figure out list comprehensions and tail recursion.
It's like what's wrong with C++ metaprogramming - you have to learn a whole new
language. D metaprogramming can be done using ordinary D functions. Nothing new
to learn.
More information about the Digitalmars-d
mailing list