Skip to content

Instantly share code, notes, and snippets.

@narumij
Created January 17, 2011 23:16
Show Gist options
  • Save narumij/783682 to your computer and use it in GitHub Desktop.
Save narumij/783682 to your computer and use it in GitHub Desktop.
//
// JNCons.h
// AnimationLanguage
//
// Created by narumij on 11/01/18.
// Copyright 2011 narumij. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface JNCons : NSObject {
id car;
id cdr;
}
@property(nonatomic,retain) id car,cdr;
+(id)cons:(id)car :(id)cdr;
+(id)arrayWithArray:(NSArray*)array;
+(int)allocatingCount;
-(id)last;
-(void)addObject:(id)obj;
-(id)objectAtIndex:(NSUInteger)index;
-(NSString*)description;
-(NSString*)stringValue;
-(NSArray*)array;
@end
#define CONS(car,cdr) [JNCons cons:car :cdr]
#define CAR(cons) [cons car]
#define CDR(cons) [cons cdr]
#define CADR(cons) [[cons cdr] car]
#define CDDR(cons) [[cons cdr] cdr]
//
// JNCons.m
// AnimationLanguage
//
// Created by narumij on 11/01/18.
// Copyright 2011 narumij. All rights reserved.
//
#import "JNCons.h"
static int cons_count = 0;
@implementation JNCons
@synthesize car,cdr;
+(id)cons:(id)car :(id)cdr
{
JNCons *cons = [JNCons new];
cons.car = car;
cons.cdr = cdr;
return [cons autorelease];
}
+(id)arrayWithArray:(NSArray*)array
{
JNCons *cons = nil;
for ( id obj in array ) {
if ( cons == nil )
cons = CONS( obj, nil );
else
[[cons last] setCdr:CONS(obj,nil)];
}
return cons;
}
-(NSArray*)array
{
NSMutableArray *anArray = [NSMutableArray new];
JNCons *cons = self;
while ( cons && [cons isKindOfClass:[JNCons class]] ) {
[anArray addObject:cons.car];
cons = cons.cdr;
}
if ( cons != nil )
[anArray addObject:cons];
return anArray;
}
- (id) init
{
self = [super init];
if (self != nil) {
++cons_count;
}
return self;
}
- (void) dealloc
{
--cons_count;
[super dealloc];
}
+(int)allocatingCount
{
return cons_count;
}
-(id)last
{
JNCons *cons = self;
while ( [cons cdr] && [[cons cdr] isKindOfClass:[JNCons class]])
cons = [cons cdr];
return cons;
}
-(void)addObject:(id)obj
{
if ( self.car == nil )
{
self.car = obj;
return;
}
JNCons *last = [self last];
last.cdr = CONS(obj,nil);
}
-(id)objectAtIndex:(NSUInteger)index
{
JNCons *cons = self;
for (int i = 0; i < index; ++i) {
cons = [cons cdr];
}
return [cons car];
}
-(NSString*)stringValue
{
if ( self.car == nil && self.cdr == nil )
return @"()";
NSString *description = @"(";
JNCons *cons = self;
int i = 0;
for ( ; cons && [cons isKindOfClass:[JNCons class]]; ++i, cons = cons.cdr ) {
description = [description stringByAppendingFormat:
i == 0 ? @"%@" : @" %@",
[cons.car description]];
}
if ( cons != nil )
return [description stringByAppendingFormat:@". %@)",cons];
return [description stringByAppendingFormat:@")"];
}
-(NSString*)description
{
return [NSString stringWithFormat:@"%@ %@",[super description],[self stringValue]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment