Syntax Highlighting

Monday, 7 January 2013

Passing Functions in D

So, the problem is to create a function (foo) that:
  • takes two values xand x2.
  • returns a a function that 
    • takes as argument a single number
    • return the  interpolated value between the two intial values
For example:
x1 = 10
x2 = 15
f(x1, x2) = (x2 - x1)*t + x1 = F(t)
F(0.5) = 12.5


import std.stdio;

auto interp_proc_maker(float x1, float x2){
    float interp(float s) {
        return (x2-x1)*s+x1;}
    return  &interp;}

void main()
{
  auto f1 = interp_proc_maker(10, 15);
  writefln("f1(0.5) = %f", f1(0.5));
}

$ gdc example.d
$ ./a.out
f1(0.5) = 12.500000

No comments:

Post a Comment