[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Accumulator



Paul Prescod <paul@prescod.net> writes:

> > i've also read a thread explaining that because of list comprehension,
> > map/reduce/filter were more or less deprecated.
> > 
> > i've yet to see examples where functional programming can be done the
> > OO way.
> 
> Well I just showed how you can emulate a closure. I guess I don't know
> what you mean. And I don't think that there is any occurrence of
> map/filter that cannot be replace by a list comprehension (except for
> corner cases where Guido decided to use slightly different semantics, in
> particular with lists of different lengths). Can you give an example.

well, you didn't talk about "reduce". The main pb with list
comprehensions is that they are limited to giving lists as a result.

i won't add examples of use of "reduce" which have already been given,
and some people may reject them as too complicated.

but there are much simpler functions that can use lambdas (some
examples are in ruby below):

- "find" using a function

file = "ls"
dir = ENV["PATH"].split(":").find{|dir| File.executable?("#{dir}/#{file}")}

- "sort" with a function (cf the perl-called-Schwartzian-transform)

there are many more use that i haven't put there since they can be
achieved quite easily with temporary lists.

- things that want to destroy an object ASAP can be written:

open("file"){|f| ... }

(C# has this, but i can't remember its name)

- things like 
  perl's s/(foo?)/f($1)/e or 
  ruby's sub('(foo?)'){|s| f(s)}

  this is a kind of conditional mapping, but i don't think it can be
  achieved via list comprehension.

- "partition"/"splitAt" which return elements matching something in one list,
and others in another.

- many other functional constructs (unfoldr, nubBy, findIndex,
unionBy, groupBy, insertBy, span, 

> 
> > ...IMO this is /somewhat/ orthogonal. And list comprehension are
> > another way of writing *some* functional programming, but are really
> > limited to lists whereas functional programming is not! (think
> > variants)
> 
> Once again, can you give an example?

- manipulating data structures like XML trees: the "map" can transform
an XML tree into another tree (a la XSLT)