Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of formulas

I want to make an objective c array in xcode with formulas like this..

  • x+5
  • x-5
  • x/5
  • x*5

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?

like image 566
rjf0909 Avatar asked Aug 22 '13 02:08

rjf0909


2 Answers

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.

like image 174
Lucas Eduardo Avatar answered Oct 27 '22 15:10

Lucas Eduardo


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.)

like image 26
Rob Napier Avatar answered Oct 27 '22 15:10

Rob Napier