Caleb Madrigal

Programming, Hacking, Math, and Art

 

Reduce with Python and Clojure

I was just playing around writing an annuity calculator function. Here is my first version:

def calculate_annuity(years, interest=0, addition_per_year=0, starting_amount=0):
    result = []
    running_total = starting_amount
    for year in range(years+1):
        result.append(running_total)
        running_total = (running_total + addition_per_year) * (1 + interest)
    return result

Here is a 2nd version, written using reduce instead of a loop:

def calculate_annuity2(years, interest=0, addition_per_year=0, starting_amount=0):
    return reduce(lambda result,addition: result + [(result[-1] + addition) * (1 + interest)],
                  [addition_per_year] * years, [starting_amount])

And here is a version in Clojure (basically a direct translation of the Python one:

(defn annuity [years interest addition_per_year init]
    (reduce
        #(conj %1 (* (+ (last %1) %2) (+ 1 interest)))
        [starting_amount]
        (for [i (range years)] addition_per_year)))

Here are some example use cases:

; Find investment returns by year for a $1000 investment ...

NSArray+FP

I realized that I utilize the [NSArray head] and [NSArray tail] functions in various code snippets, but haven.t shared the actual code for that category. So here is my NSArray+FPcode.

NSArray+FP.h

#import <Foundation/Foundation.h>
typedef id(^MapBlock)(id);
@interface NSArray (FP)
- (NSArray *)map:(MapBlock)block;
- (id)head;
- (NSArray *)tail;
@end

NSArray+FP.m

#import "NSArray+FP.h"
@implementation NSArray (FP)

- (NSArray *)map:(MapBlock)block {
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    for (id object in self) {
        [resultArray addObject:block(object)];
    }
    return resultArray;
}

- (id)head
{
    return [self objectAtIndex:0];
}

- (NSArray *)tail
{
    NSRange tailRange;
    tailRange.location = 1;
    tailRange.length = [self count] - 1;
    return [self subarrayWithRange:tailRange];
}

@end

Functional programming to deal with asynchronicity in Objective-C

In the last few weeks, I've used the [ALAssetsLibrary loadImages:callback:] method to load a list of images. For what I was doing, I wanted to wait till all the images were loaded before proceeding. I found that I could solve this problem very elegantly using a recursive solution:

- (void)loadImages:(NSArray *)imageUrls loadedImages:(NSArray *)loadedImages 
                                        callback:(void(^)(NSArray *))callback
{
    if (imageUrls == nil || [imageUrls count] == 0) {
        callback(loadedImages);
    }
    else {
        NSURL *head = [imageUrls head];
        __unsafe_unretained id unretained_self = self;        
        ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:head resultBlock:^(ALAsset *asset) {
            ALAssetRepresentation *assetRepresentation = asset.defaultRepresentation;

            UIImage *image = [UIImage imageWithCGImage:assetRepresentation.fullResolutionImage 
                              scale:assetRepresentation.scale
                              orientation:(UIImageOrientation)assetRepresentation.orientation];

            [unretained_self loadImages:[imageUrls tail] loadedImages:[loadedImages 
                arrayByAddingObject:image] callback:callback];
        } failureBlock:^(NSError *error) {
            [unretained_self loadImages:[imageUrls tail] loadedImages:loadedImages callback:callback];
        }];
    }
}

In ...

How to reference self in a block in Objective-C

When using ARC (automatic reference counting) in Objective-C, you need to be careful to avoid causing retain cycles. One place where a retain cycle can occur is where self is referenced in a block. To avoid a retain cycle, you can use the __unsafe_unretained modifier as such:

__unsafe_unretained id unretained_self = self;
reachability = [Reachability reachabilityWithHostname:@"maps.google.com"];
reachability.reachableBlock = ^(Reachability *r) {
    dispatch_async(dispatch_get_main_queue(), ^{
        SurveyFormController *myself = unretained_self;
        self.mapView.reachable = YES;
        [myself configureView];
    });
};

Tail call optimization in Python

Since I've been getting into functional programming more recently, the fact that Python doesn't do tail-call optimization has been bothering me. So I did a bit of searching, and found this gem: Tail Call Optimization Decorator.

Here is a snippet from it:

import sys

class TailRecurseException:
  def __init__(self, args, kwargs):
    self.args = args
    self.kwargs = kwargs

def tail_call_optimized(g):
  """
  This function decorates a function with tail call
  optimization. It does this by throwing an exception
  if it is it's own grandparent, and catching such
  exceptions to fake the tail call optimization.

  This function fails if the decorated
  function recurses in a non-tail context.
  """
  def func(*args, **kwargs):
    f = sys._getframe()
    if f.f_back and f.f_back.f_back \
        and f.f_back.f_back.f_code == f.f_code ...

Function application and function composition in Haskell

In the process of learning haskell, I've been trying to become comfortable with the function applicator ($) and function composition (.). Here is some code to show how they relate (and how they relate to using parenthesis to enforce order of operations):

let dict = [(1,'a'),(2,'b'),(3,'c')]
-- The following 3 lines of code are equivalent...
snd . head . filter (\item@(k,v) -> k == 2) $ dict -- returns 'b'
snd $ head $ filter (\item@(k,v) -> k == 2) dict -- returns 'b'
snd (head (filter (\item@(k,v) -> k == 2) dict)) -- return 'b'

Map in Objective-C

Today, I was faced with an issue several times where I had an array of items of one type, and had to convert this into an array of items of a different type. This made me really want a map() function. So I added one to NSArray like so:

NSArray+FP.h

#import <Foundation/Foundation.h>
typedef id(^MapBlock)(id);
@interface NSArray (FP)
- (NSArray *)map:(MapBlock)block;
@end

NSArray+FP.m

#import "NSArray+FP.h"
@implementation NSArray (FP)
- (NSArray *)map:(MapBlock)block {
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    for (id object in self) {
        [resultArray addObject:block(object)];
    }
    return resultArray;
}
@end

So now, I can do this!

NSArray *strArray = [NSArray arrayWithObjects:@"1",@"1",@"2",@"3",@"5",@"8",nil];
NSArray *numArray = [strArray map:^id(id object) {
    NSString *str = object;
    return [NSNumber ...

First steps in haskell

Just started looking into the Haskell programming language by going through the first few chapters of the awesome book: Learn You a Haskell which is free to read online. Here are some things I really like about what I have seen of Haskell so far:

  • Type inference allows you to have static typing but not all the verbosity of most other statically-typed languages.
  • Lazy evaluation is huge in Haskell, and it lets you do things like this: let factorial n = product (take n [1..]) So here, we have an infinite list ([1..] creates a infinite list from 1 to infinity!) which from which the first n items are taken and passed to the product function. Awesomeness...
  • Nice REPL