[chuck-users] Functional Chuck?
Michael Heuer
heuermh at gmail.com
Sun Jun 8 16:33:57 EDT 2008
mike clemow wrote:
> Hey folks,
>
> Anyone else really wish that Chuck supported higher order functions???
>
> check it out. This doesn't work, but i'd love for it to work:
>
> // a function that returns an int
> fun int fn( int n ) {
> return n + 3;
> }
>
> // a function that takes a function and an array of ints
> // and returns an array of ints which correspond to the action
> // of that function on each int in the original array
> fun int[] mapInt( function fn, int list[] ) {
> int results[list.cap()];
> for( 0 => int i; i < list.cap(); i++ ) {
> fn( list[i] ) => results[i];
> }
> return results;
> }
>
> [1, 2, 3, 4, 5] @=> input;
>
> Add3 add3;
>
> mapInt( add3, input ) => int output[];
>
> <<< output[2] >>>; // should print 6
>
> --
>
> I just wish that functions could take other functions as parameters
> and return functions as their return value. I think that would make
> sense. Functions, I find are more powerful than classes in Chuck.
>
> Also, why is "function" a keyword?
>
> cheers,
> mike
Hello Mike,
You can do this with functors, small classes that are functions.
There is a thread on the forum with some example code, but it is
basically just
class Function
{
fun int doIt(int n) { ... }
}
fun void int[] mapInt(Function f, int list[]) { ... }
michael
More information about the chuck-users
mailing list