Why is std.algorithm so complicated to use?

Christophe Travert travert at phare.normalesup.org
Tue Jul 10 08:11:59 PDT 2012

Jacob Carlborg , dans le message (digitalmars.D:171685), a écrit :
> I mean, is it possible to have the original code work?
> auto bar = foo.chain("bar");
> Or perhaps more appropriate:
> auto bar = foo.append("bar");

What is wrong with foo.chain(["bar"])?

If you do not want the heap allocation of the array, you can create a 
one-element range to feed to chain (maybe such a thing could be placed 
in phobos, next to takeOne).

struct OneElementRange(E)
  E elem;
  bool passed;
  @property ref E front() { return elem; }
  void popFront() { passed = true; }
  @property bool empty() { return passed; }
  @property size_t length() { return 1-passed; }

You can't expect chain to work the same way as run-time append. A 
compile-time append would be very inefficient if misused.

> https://github.com/jacob-carlborg/dstep/blob/master/dstep/translator/Translator.d#L217

you might try this (untested)

string function(Parameter) stringify = (x)
 return (x.isConst? "const("~x.type~")": x.type)
    ~ (x.name.any?" "~translateIdentifier(x.name):"");

auto params = parameters
  .chain(variadic? []: ["..."])
  .joiner(", ");

context ~= params;

I am not sure this will be more efficient. joiner may be slowed down by 
the fact that it is called with a chain result, which is slower on 
front. But at leat you save yourself the heap-allocation of the params 

I would use:
context ~= parameters.map!stringify().joiner(",  ");
if (variadic) context ~= ", ...";

To make the best implementation would require to know how the String 
context works.

*Note that here, stringify is not lazy, and thus allocates. It 
could be a chain or a joiner, but I'm not sure the result would really 
be more efficient.

More information about the Digitalmars-d mailing list