Skip to content

Instantly share code, notes, and snippets.

@hughrawlinson
Created June 23, 2016 21:21
Show Gist options
  • Save hughrawlinson/793c4133fd90ce66b797412b95ded488 to your computer and use it in GitHub Desktop.
Save hughrawlinson/793c4133fd90ce66b797412b95ded488 to your computer and use it in GitHub Desktop.
Functional Staples, in ChucK

Functional Functions in ChucK

Here's a set of iterative solutions to map, reduce, and filter, in ChucK. Should probably have gone recursive. Next time.

Somewhat hampered by ChucK missing a higher-order function feature, and the fact that the ChucK type system doesn't support generics or typeclasses, so I implemented classes to wrap them from which they can be extended.

I'd almost consider attempting to implement higher-order functions in ChucK myself after this, except that I'd almost definitely need to do a lot of type-inference code.

fun int[] map (int a[], Function f) {
int b[0];
for (0 => int i; i < a.size(); i++) {
b << f.apply(a[i]);
}
return b;
}
fun int reduce (int a[], reduceFunction f, int accumulator) {
accumulator => int z;
for (0 => int i; i < a.size(); i++) {
z => int y;
f.apply(a[i], y) => z;
}
return z;
}
fun int reduce (int a[], reduceFunction f) {
return reduce (a, f, 0);
}
fun int[] filter ( int a[], Function f ) {
int b[0];
for (0 => int i; i < a.size(); i++) {
if (f.apply(a[i])) {
b << a[i];
}
}
return b;
}
class Function {
int default;
fun int apply(int a){
return default;
}
}
class reduceFunction {
int default;
fun int apply(int a, int b) {
return default;
}
}
// The following is code to demonstrate the above functions
class Double extends Function {
fun int apply(int a){
return a * 2;
}
}
class Sum extends reduceFunction {
fun int apply(int a, int b) {
return a + b;
}
}
class IsEven extends Function {
fun int apply(int a){
if(a % 2 == 0){
return 1;
}
else {
return 0;
}
}
}
Double double;
Sum sum;
IsEven isEven;
map([1,2,3,4], double); // [2,4,6,8]
reduce([1,2,3,4], sum); // 10
filter([1,2,3,4],isEven); // [2,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment