www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Efficiency of functional code

reply bearophile <bearophileHUGS lycos.com> writes:
(The topic of this post is just one: efficient compilation of code that uses
higher order functions a lot. This post is not really about Haskell, or many
other things.)

I am learning more Haskell, and I am back-translating most of my Haskell code
to D2 too. I am getting more experience on code like this, that performs a
Schwartzian sort:

swsort key = map snd . sortBy (comparing fst) . map (key &&& id)

In that code this unusual arrow:
(key &&& id)
means something like this lambda:
\x -> (key x, x)

In Haskell many of my functions are 1 line long, and often less than four
lines. So the comment that Walter says often against shallow single-line Phobos
functions doesn't apply to Haskell :-)

In Haskell code loops, explicit recursion, and even lambdas are not common.
Even blocks of pattern matching inside a function are less appreciated than
functions defined one piece at a time with pattern matching on just their
arguments.

I am also doing many benchmarks. One thing I'm seeing is that the GHC Haskell
compiler is very good at removing the overhead of higher-order functions (much
better than DMD). If D wants to encourage functional-style code, that uses a
lot the higher order functions of Phobos, then I think the D compiler has to
learn to compile them quite better than now. I don't have enough experience of
compilers yet, so I don't know how to do this. (I just think that the
"conditional purity" feature will help compile better the Phobos HOFs).

Bye,
bearophile
May 21 2011
parent "Simen Kjaeraas" <simen.kjaras gmail.com> writes:
On Sun, 22 May 2011 02:05:11 +0200, bearophile <bearophileHUGS lycos.com>  
wrote:

 In Haskell many of my functions are 1 line long, and often less than  
 four lines. So the comment that Walter says often against shallow  
 single-line Phobos functions doesn't apply to Haskell :-)
This is so true. Factoring functions is not just about making code shorter, but grouping constructs in such a way as to more clearly describe the actions performed. -- Simen
May 22 2011