How do I REALLY do math with NSNumbers? (lisp implementation in obj-c)

inspired by Clojure and Peter Norwig

I'm trying my best to implement simple Lisp in obj-c. I have many basics (including cool cocoa integration similar to Clojure) and I would like to move on to arithmetic.

A little bit about how I have done so far: I use the tiny "Scope" class, which is just NSMutableDictionary for local vars with a pointer to the parent "Scope". (AKA, I am only limited to storing objects.)

I parse the numbers with the following rule: a prime number, such as 2 or 2.7, is converted to [NSNumber numberWithIneger:] or [NSNumber numberWithDouble:] . But for cocoa integration, you can also do things like 2i or 4U to create an NSNumber with a special scalar type. (I also created a category around NSObject and made a new performSelector:withObjects: method that skillfully decompresses the arguments and windows support the return type to actually make this useful)

I have a special form that looks like this: (static Math add: 1 2 3 4) , which turns into a call to the obj-c method, which looks like this: [Math add:args]

Given all this, my question is for all of you good people: what is a good way to implement the add: method?

I was hoping to do something similar to the way I think clojure does (uses?) It, implementing a bunch of methods like add:(int)x to:(long)y , add:(long)x to:(float)y etc. etc., through all possible combinations, and abbreviation of the args list, adding everything. But, of course, obj-c does not support such overriding methods. Besides the restriction on adding only to NSIntegers and doubling, is there any trick I can do to get to where I want? It doesn't even seem to me that this is super-efficient (although this is always a plus!)

+8
objective-c lisp
source share
1 answer

A simple way: just turn all numbers into double when doing arithmetic and ignore problems with casting and precision.

Another option is to use NSDecimalNumber instead of NSNumber everywhere. There is a method +[NSDecimalNumber decimalNumberWithString] , which you can use for boxing, as well as methods for performing arithmetic with multiple NSDecimalNumber s. Of course, you have more overhead in this way, but I believe that performance is not a primary concern.

+1
source share

All Articles