# [chuck-users] Functional Chuck?

mike clemow gelfmuse at gmail.com
Sun Jun 8 16:50:42 EDT 2008

```Okay that's really interesting.  I thought about doing this last
night, but I found it kind of frustrating.  I'll see what I can do
and see what I can come up with.

Thanks!

-Mike

PS: Here's the really simple example with functors:

class Function {
fun int fn( int n ) {
return n + 3;
}
}

fun int[] mapInt( Function fn, int list[] ) {
int results[list.cap()];
for( 0 => int i; i < list.cap(); i++ ) {
fn.fn( list[i] ) => results[i];
}
return results;
}

[1, 2, 3, 4, 5] @=> int input[];

mapInt( add3, input ) @=> int output[];

<<< output[2] >>>;  // prints 6

On Sun, Jun 8, 2008 at 4:38 PM, Michael Heuer <heuermh at gmail.com> wrote:
> On Sun, Jun 8, 2008 at 3:33 PM, Michael Heuer <heuermh at gmail.com> wrote:
>> 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;
>>>
>>>
>>> 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
>>
>
>
> http://electro-music.com/forum/topic-23546.html
>
>   michael
> _______________________________________________
> chuck-users mailing list
> chuck-users at lists.cs.princeton.edu
> https://lists.cs.princeton.edu/mailman/listinfo/chuck-users
>

--
http://semiotech.org