I am experimenting with learning C and Currying (after learning a bit of Haskell the other day) and I wanted to know if it was possible to do something similar in C.
This is purely "for fun", I've looked at GCC and see that it supports nested functions (non-standard) so was wondering if this approach would work.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
uint32_t (*addCur(uint32_t ad))(uint32_t ad) {
uint32_t add(uint32_t to) {
return ad + to;
}
return add;
}
int main(int argc, char **argv) {
uint32_t a = 1, b = 2;
if(argc > 1)
a = atoi(argv[1]);
if(argc > 2)
b = atoi(argv[2]);
uint32_t result = addCur(a)(b);
printf("result: %d\n", result);
return 0;
}
Which when run gives me the desired effect I am looking for.
./Currying 5 7
result: 12
What I'd like to do is to implement a "multiply and add" method. So in essence have three nested functions, where each function returns the function but leaves the necessary scope to the appropriate variables.
I.E. in JavaScript you can do the following:
let multiplyAndAdd = (x) => (y) => (z) => (x*y) + z;
multiplyAndAdd(3)(4)(5);
Which gives 17.