I want to make an objective c array in xcode with formulas like this..
So I can load a formula with arrayName[i] and give the value of x and get the answer. Is there a way to do this, if so how?
You can achieve this with an array of blocks. Each block would receive a parameter x
and return a value, calculating one function of yours. Then, you can select any position of the array and execute it.
It will be something like this:
typedef CGFloat (^MyFunction)(CGFloat); //using a typedef to ease the heavy syntax of the blocks
MyFunction function1 = ^CGFloat(CGFloat x){
return x + 5;
};
MyFunction function2 = ^CGFloat(CGFloat x){
return x - 5;
};
MyFunction function3 = ^CGFloat(CGFloat x){
return x / 5;
};
MyFunction function4 = ^CGFloat(CGFloat x){
return x * 5;
};
NSArray *functions = @[function1, function2, function3, function4];
Now you can access any position of the array, and execute the chosen block, like this:
MyFunction myFunction = functions[3];
CGFloat test = myFunction(5); //test will hold 25, because the selected block is 'x * 5'
You can obviously change the 3
for any index of the array. And of course, you can declare any other functions like the ones above and add them in your array.
I have tested and it works well. Hope it helped.
Not to detract from Lucas's answer, but it's worth pointing out how powerful this can really be. It's difficult to get all the power of functional programming this way (particularly since the syntax starts to get in the way), but you can get many of the pieces. For example, since these blocks are created at runtime, you can create new functions on the fly. For example, you can have a function that returns a custom function:
typedef CGFloat (^MyFunction)(CGFloat);
MyFunction addXFunction(CGFloat toAdd) {
return ^CGFloat(CGFloat x) {
return x + toAdd;
};
}
MyFunction addFive = addXFunction(5);
CGFloat fifteen = addFive(10);
And of course you can even do things like map
and reduce
, though the syntax is not quite as simple as in a true functional language:
NSArray * number_map(MyFunction f, NSArray *numbers) {
NSMutableArray *result = [NSMutableArray new];
for (NSNumber *number in numbers) {
[result addObject:@(f([number floatValue]))];
}
return result;
}
NSArray *numbers = @[@(1), @(2), @(3), @(4), @(5)];
MyFunction addFive = addXFunction(5);
NSArray *numbersPlusFive = number_map(addFive, numbers));
(I continue to be amazed that NSArray
has no -map
method built-in. If this bothers you, dupe rdar://14807617.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With