D Programming Language 2.0

- Comments
- D
- Search
- Home

Last update Sat Feb 14 12:00:02 2009

# std.functional

Functions that manipulate other functions.
Author:
Andrei Alexandrescu

template unaryFun(alias comp,bool byRef = false)
  Transforms a string representing an expression into a unary function. The string must use symbol name a as the parameter.
  Example:

      alias unaryFun!("(a & 1) == 0") isEven;
      assert(isEven(2) && !isEven(1));

template binaryFun(alias comp)
  Transforms a string representing an expression into a Boolean binary predicate. The string must use symbol names a and b as the compared elements.
  Example:

      alias binaryFun!("a < b") less;
      assert(less(1, 2) && !less(2, 1));
      alias binaryFun!("a > b") greater;
      assert(!greater("1", "2") && greater("2", "1"));

template adjoin(F...)
  Takes multiple functions and adjoins them together. The result is a std.typecons.Tuple with one element per passed-in function. Upon invocation, the returned tuple is the adjoined results of all functions.
  Example:

      static bool f1(int a) { return a != 0; }
      static int f2(int a) { return a / 2; }
      auto x = adjoin!(f1, f2)(5);
      assert(is(typeof(x) == Tuple!(bool, int)));
      assert(x._0 == true && x._1 == 2);

template compose(fun...)
  Composes passed-in functions fun[0], fun[1], ... returning a function f(x) that in turn returns fun[0](fun[1](...(x))).... Each function can be a regular functions, a delegate, or a string.
  Example:

      // First split a string in whitespace-separated tokens and then
      // convert each token into an integer
      assert(compose!(map!(to!(int)), split)("1 2 3") == [1, 2, 3]);

template pipe(fun...)
  Pipes functions in sequence. Offers the same functionality as compose, but with functions specified in reverse order. This may lead to more readable code in some situation because the order of execution is the same as lexical order.
  Example:

      // Read an entire text file, split the resulting string in
      // whitespace-separated tokens, and then convert each token into an
      // integer
      int[] a = pipe!(readText, split, map!(to!(int)))("file.txt");

Copyright © 1999-2009 by Digital Mars, All Rights Reserved | Page generated by Ddoc.