Functions in an array?

edited February 2014 in Programming Questions

Hi, I was wondering if it was possible to pass functions in an array.

I have seven functions that produce patterns, I wanted to know if I could put them in an array which I can then use in a 'for i' statement and rotate each odd number in the array anti-clockwise and each even number clockwise.

Tagged:

Answers

  • You have to wrap each function in a class.

  • Example, using anonymous classes made after an interface:

    interface F
    {
      float f(float v);
    }
    
    F[] functions =
    {
      new F() { float f(float v) { return v * 2; } },
      new F() { float f(float v) { return v + 20; } },
      new F() { float f(float v) { return v * v; } },
    };
    
    void setup()
    {
      float val = 3.14;
      for (int i = 0; i < functions.length; i++)
      {
        println(functions[i].f(val));
      }
    }
    
  • edited February 2014

    Java doesn't have the function type! Hence it can't store such references in variables! 8-X
    However, we can use methods from interfaces & classes as sorta replacement as @PhiLho has shown above.
    Some other languages can though. Like JavaScript, Lua, C, etc.! :ar!
    Java 8's gonna get something similar soon! <:-P

  • Wow, cool (Java 8)

    Yea, just use a class.

  • edited February 2014

    I wouldn't have my hopes too high too soon in regards to Processing + Java 8.
    Shamefully, Processing's pre-processor got problems even w/ something as basic as enum.
    Imagine when dealing w/ lambda expressions or method references!

  • I usually just store a commandID and name the different commands (which are just int)

    and then I have a function somewhere

    void excuteCommandID (commandID)
    switch (commandID) { 
    case cmdGoLeft:
     // call a function
    break;
    
  • (which are just int)

    Java 7 accepts String for switch ()! :-c

  • To be pedantic, encapsulating a single function inside a general class is called the Command pattern. It is a very useful design pattern to know. :-)

Sign In or Register to comment.