RSS
 

Beginner’s LISP — PART 2

18 Aug

I picked out a nice exercise from the SICP book for this second installment of my series for beginner Scheme programmers (like myself). I chose Exercise 1.3 which reads as follows:

“Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers”

My goal is to show a simple yet somewhat clever solution. My first thought on how to accomplish this is to just test all 3 possible cases. This seems like a rather bland approach however and from what I understand, LISP is supposed to be exciting :) . As a result, I’m going to go with a less efficient but more readable implementation. I’m going to add the squares of all three numbers and then subtract the square of the smallest.

(define (sicp1.3 a b c)
    (- (+ (* a a) (* b b) (* c c))
        (* (min a b c)(min a b c))))

Here I define a procedure called “sicp1.3″ that takes 3 arguments. I then add the squares the those 3 args and subtract the square of the smallest. If you are not able to see how this code does what I described, then checkout my earlier post.

Now, I already admitted that this is not an optimally efficient algorithm, so I better make this at least a little easier on the eyes. First by pulling out the “square of the minimum value” part to it’s own procedure. That gives us:

(define (sqmin a b c)
  (* (min a b c)(min a b c)))

(define (sicp1.3 a b c)
  (- (+ (* a a) (* b b) (* c c))
     (sqmin a b c)))

and finally, I’d say that the “sum of squares” part should really be it’s own procedure as well

(define (sqmin a b c)
    (* (min a b c)(min a b c)))

(define (sumsq a b c)
    (+ (* a a) (* b b) (* c c)))

(define (sicp1.3 a b c)
  (- (sumsq a b c)
      (sqmin a b c)))

So thats what I’ve got. Upon looking this up on Stackoverflow I found a similar solution to the one given here, plus a number of much more sophisticated examples. Enjoy!

 
No Comments

Posted in General

 

Polyglot Stall

13 Jul

I would consider myself a polyglot programmer. Whenever I need to design a new piece of software, I take time to consider what technology or technologies to use. Most readily at hand are Objective-C, Ruby, BASH, C, Javascript, and Erlang, but I will also spend time thinking of anything else that could be a good fit. This leads to a state that I am going to term “Polyglot Stall”. This is when you are architecting a moderate to large system, and get stuck in a cyclical thought pattern in which you keep changing design and implementation language indefinitely. For me it often starts with deciding if code should live on the server side, client side, or both. I’m currently stuck in one of these situations. I’m continually shuffling functionally between a webapp on the server side and an OSX app on the client side. Sometimes I decide that with Javascript and CSS3 I don’t need the client at all, sometimes I decide that it should all be in the Objective-C app. Sometimes it seems like I should store data in a remote MongoDB instance, sometimes in the file system. It’s quite exhausting.

It occurs to me, that if I were a J2EE developer it wouldn’t even be a question. I might not choose the most efficient design, but I would start writing the damn thing and I eventually would get it all working. I don’t think I’ll be cloistering myself in with any particular technology anytime soon, but it does seem a little less tiring. It is a really difficult thing to balance. You want to consider every possible combination of solutions, but you also want to maintain your sanity.

What I’d really like to do is find a way to move forward. To break the cycle and get on with it. I can hear the Agile Development guys/girls in my head already, “Choose a concrete problem, solve that, and refactor later”. Well generally I agree, but there are situations where that just won’t work. When you are designing a full scale platform on which many things will be based, you have to get the basic gist done up front.
I find that the solution is to make decisions at a higher level before dropping down to the implementation. You’ve got to look at what the thing is going to do before you decide how you are going to do it. If both elements are variable you are going to loop forever.

while(I.can_change_everything){
    I.change(rand(10));
}

You have to lock things down at some level of abstraction. If you only program in one way, then that’s a given. But for those of us who are up for anything and obsessed with finding the best way to accomplish something, it is definitely not. Often just making one firm decision can set everything in motion. Hopefully that happens sometime soon, before I climb a clock tower and start tossing live Emus over the edge. During mating season of course.

 
No Comments

Posted in General

 

Why it is so much harder to do TDD with iPhone development than with Rails.

06 Jun

So, this weekend I attended a “Hackibou” event hosted by the Cleveland Ruby Brigade. It was a good time. We pair-programmed through a very simple code kata using TDD with Ruby as the language and RSpec as the test framework. I really enjoyed the experience of doing true TDD. Although the code we were writing was basically trival, I was able to imagine using this process on projects of arbitrary complexity.

Several months ago, after attending CodeMash, I had a similar experience and was determined to start using TDD for my day job, which is iPhone development. Well, after this recent reminder, it occurs to me that I have totally failed. Even though I believe in TDD and am able to work that way on Rails projects, I have been unable to get the ball rolling on my iPhone projects. The big question is, “Why?”.

I think there are 4 reasons

  1. MVC — It is really easy to put way too much code in the controller in an iPhone app.
  2. Rendered HTML is very testable, a rendered UIView is less testable.
  3. Objective-C is dynamic, but Xcode likes to pretend that it doesn’t know that. This makes testing frameworks like RSpec, that inject methods at runtime, throw tons of warnings when ported.
  4. This one is big (big enough for caps): THE IPHONE DEV CULTURE DOESN’T DEMAND IT! AND IT SHOULD!!

Read the rest of this entry »

 
No Comments

Posted in General

 

Resizing images with Ruby and RMagick

17 May

I recently was faced with a very large number of images that all needed to be resized. They were of varying formats and all needed to be stretched to double size. I’m sure there are lots of different ways to handle this situation, but as usual I went the Ruby way. RMagick seemed to be one of the top gems out there for doing this. It is a very powerful image library, and installing it can be quite a process. Installing it via MacPorts worked no problem for me though on OS X. It did take quite a while however to pull down and compile all the dependencies.

Once I got it installed, I was able to knock this script out in no time. It takes a path to either a single file or directory as it’s first argument. If a directory is given, it will resize all images in that directory (non-recursively). As it’s second argument it takes a floating point number representing the level you want to resize to. 1.0 would be 100%, 0.5 would be 50%, 1.4 would be 140%, you get it. The script creates a subdirectory in the directory where the file or files being resized live, named ‘resized_to_X’ where ‘X’ is the level you choose. It writes the new files into this dir. It also gives you a nice print out as it processes each file, displaying the dimensions of the original and new images.

Special thanks to Joe Pecoraro for showing me some tips on dealing with file paths generically.

#!/usr/bin/ruby
require 'rubygems'
require 'rmagick'
include Magick

#Author: Joe Cannatti
#Date: 5/5/2010
#Description: Resizes dimensions of any format image , or all images in a dir

USAGE = "Usage: resize_image.rb (dirname|filename) value #value is a float"
IMG_EXP = /\.(png|jpg|gif|jpeg)$/

def resize(_img,_ratio, filename, _write_dir)
  re_img = _img.scale _ratio.to_f
  write_path = File.basename filename
  re_img.write File.join _write_dir, write_path
  print_file_resize_header filename, _img, re_img
end


def make_output_dir(dirPath)
  if not File.directory? dirPath
    Dir.mkdir dirPath
  end
end

#return the output directory from an input directory

def output_dir(input_path)
  parent, basename = File.split input_path
  if parent == "." then
    resize_dir
  else
    File.join parent, resize_dir
  end
end

#print  methods

def print_file_resize_header(filename, _img, _re_img)
  puts "File: #{filename}"
  puts "------------------------------------------\n"
  puts "\tOriginal Size"
  puts "\t-------------"
  puts "\t#{_img.columns} X #{_img.rows}\n\n"
  puts "\tResized to"
  puts "\t-------------"
  puts "\t#{_re_img.columns} X #{_re_img.rows}"
  puts
end

def print_dir_header(path)
  puts "Reading Directory named: #{path}"
  puts "--------------------------------------------------------------------"
  puts
end

def resize_dir
  "resized_to_#{ARGV[1]}"
end

begin
  raise "Wrong paramater count" unless ARGV.length == 2
  puts

  if ARGV[0] =~ IMG_EXP then
    dirPath = output_dir ARGV[0]
    make_output_dir dirPath
    img = (Image.read ARGV[0])[0]
    resize img, ARGV[1], ARGV[0], dirPath
  else
    dirPath = File.join ARGV[0], resize_dir
    make_output_dir dirPath
    print_dir_header ARGV[0]
    Dir.open(ARGV[0]).each do |file|
      next unless file =~ IMG_EXP
      img = (Image.read(File.join(ARGV[0], file)))[0]
      resize img, ARGV[1], file, dirPath
    end
  end
  puts
rescue Exception => e
  puts
  puts e.message
  puts USAGE
end
 
No Comments

Posted in General

 

The cool stuff about Lisp for those of us with day jobs — PART 1: Writing Your Own Addition Operator in Scheme

10 May

I have been having a great time watching the “Structure and Interpretation of Computer Programs” videos from MIT. The original ones from 1984. Something that I thought was really cool from video ‘1b’ was the implementation of the + operator. They give 2 examples of different ways to pull it off in Lisp. To be honest, although they are both very simple, neither one is really obvious if you are coming from an imperative programming background. Both assume that all we have to use is the increment and decrement operators.

In case you are totally new to Lisp, basically the first symbol after an open paren is a function, and each expression after that is a param passed to it. This pattern is nested of course.

The first approach that the professor shows is to decrement the x and increment y until x is zero
So, in C we would write this logic as the function

int add(int x, int y){
    while(x > 0){
        x--;
        y++;
    }
    return y;
}

And in Lisp it is

(define (+ x y)
    (if (= x 0)
        y
        (+ (-1 x) (+1 y))))

What’s important about this aproach is that it shows how loops in imperative languages are replaced by recursion in functional ones. What we are doing here is defining a function named ‘+’. If the x value is 0 we just return y, else we decrement x, increment y and recursively call our function again. This obviously continues until x is 0 and y is our answer. An ‘if’ expresson in Lisp takes 3 parameters,

a predicate (in C we’d say conditional)
a consequent (in C this would be the code inside the if block)
an alternative (in C this would be the code in the else block)

The predicate in this is example “(= x 0)” which means “x equals 0″
The consequent in this exmple is “y”
The alternate is the function calling itself after incrementing y and decrementing x “(+ (-1 x) (+1 y))”

So, that one seemed pretty cool to me. It’s a nice introduction to functional programming. The professor goes one step futher though and covers a slightly more mind bending, but still simple enough example. This one also terminates when x is zero but instead of incrementing y we will increment the expression that makes the recursive call.

In Lisp

(define (+ x y)
        (if  (= x 0)
            y
            (+1 (+ (-1 x) y))))

Thats pretty cool. Here is how it looks when you call this function to add the numbers 3 and 4. I will expand the function by substitution as the prof does in the video.

(+ 3 4)
(+1 (+ 2 4))
(+1 (+1 (+ 1 4)))
(+1 (+1 (+1 (0 4))))
(+1 (+1 (+1 4)))
(+1 (+1 5))
(+1 6)
7
 
2 Comments

Posted in General

 

It’s about the user!

09 Apr

People have been in quite an uproar about Apple’s new ban on some third party development tools. In case you’re not up to speed, they basically have banned anything that lets you develop in another language and then compile down to an xCode project. This includes tools like Flash, Corona, Wax, Titanium, and maybe Unity3D. It seems that most people who are angry feel that Apple is trying to rub out competitors. I really don’t think thats what’s going on here. I think it’s about keeping apps that run on the platform to a high standard.

I spent some time recently downloading a bunch of apps created this way. I won’t name any names, but I download the flagship apps for this sort of technology and had nothing but bad things to say about them. They were sluggish, glitchy, behaved in ways not typical to the iPhone, and crashed!

I think being a developer for an Apple platform is like being in an orchestra. There is room to experiment and express yourself, but in the end, if you’re messing up the Beethoven, you’re going to lose your gig. If you want to play in an orchestra you also have to learn the right instrument. If you love to play electric guitar, you can do that own your own time, but when it’s time to play at Carnegie Hall you have better have your violin with you. If you ask the conductor if you can play the cello part on key-tar instead of cello, he’s going to say “NO!”. It doesn’t mean that programmers should’t experiment. That’s what programmers do. But when it comes to releasing apps to the public, the quality should always be high. I suspect that if these frameworks had turned out better apps they wouldn’t have been called out by Apple. But the bottom line here is these toolkits suck. They are only being used by lazy developers who don’t want to take the time to learn to do it right.

 
No Comments

Posted in General

 

Replacing Unix or Windows line endings with Ruby

18 Mar

The difference in line endings on Windoze and Unix based systems is a problem that is easy to solve. It can be done with one line of sed or one command in vim. (NOTE: Both are a little on the cryptic side). But my current plan is to be able to solve every problem in the world with my ‘Scripts’ directory. It’s in my $PATH and I think of every script I write as expanding the functionality of the command line. It’s a quicker solution than the methods I listed above. This is because every time I go to use sed I have to google ‘basic sed tutorial’ and it always takes me a few minutes to come up with anything but the simplest replace command in vim. As a result I’m adding replace_line_endings.rb to my Scripts collection. But first, a little history.

Unix based systems use a single character to represent a newline ‘\n’. Most non-unix system (MS Windows, Symbian, OS/2, etc) use two characters ‘\r\n’. In the modern world there is no advantage or disadvantage for one or the other. Well, except for the extra byte required for the character. But at the time that the non-unix guys decided on ‘\r\n’ it did serve a purpose. Teletype style machines had an actual carriage that had to be dropped to the next line and returned to the left. As data was coming from an application to the Teletype, the time it took to send one character was not long enough for the carriage to make it back in time. Since the ISO standard at the time listed both ‘\n’ and \r\n’ as acceptable, the 2 character version was a nice solution.

Anyway, here is my Ruby implementation. It takes ‘-w’ (convert to Windows) or ‘-u’ (convert to Unix) as a flag. Followed by the path to the file you would like to convert. It writes the result to a file with the same name as the original but with ‘.w’ or ‘.u’ appended respectively.

#!/usr/bin/ruby

begin
  flag = ARGV[0]
  path = ARGV[1]
 
  raise "Bad Option Flag" unless flag == "-w" or flag == "-u"
 
  if flag == "-w"  then
    to_replace = "\n"
    replace_with = "\r\n"
  else
    to_replace = "\r\n"
    replace_with = "\n"
  end
 
  File.open("#{path}.#{flag[1].chr}", "w") do |f|
    File.open(path).each do |line|
      fLine = line.gsub to_replace, replace_with
      f.write fLine
    end
  end
 
rescue Exception => e
  puts "Usage: replace_line_endings -(w|u) input_filename\n#{e.message}"
end
 
No Comments

Posted in General

 

HTML is the new cursive

16 Mar

I have heard that they don’t teach cursive in elementary school anymore. This makes some sense to me. Cursive was important when handwritten script was the way we presented official or professional information. When I was in high school everyone had to take a course on MS Office. It was said to be important because everyone needs to be able to setup margins and layouts in a Word document.

I think we’re ready for another shift forward. Soon, it will be a no-brainer to state that most information is transferred through the web browser. In a world like that, I think even the least technical people within the professional world need html skills.

Currently, it is common for HTML chores to be pushed onto programmers. Having the most technical people in the office work with HTML is a total misuse of resources. HTML is a markup language, not a programming language. Obviously developers are capable of this, but it’s not where their time should be spent. HTML is very very simple.

I’d like to see HTML used as the medium that students use to turn in assignments. Instead of handing in a printed paper to a 5th grade teacher or emailing a .docx file to a professor, imagine uploading you essay to a web-server.

I propose that anyone can work with HTML just as easily as they set the margins in Word or write a cursive ‘Q’. Well, hopefully more easily than that damn ‘Q’.

 
No Comments

Posted in General

 

Generating Objective-C Code With Ruby: Part 2 — Dealloc

16 Dec

Something that I often forget until days into working with a new controller is the dealloc method. There are a lot of steps involved in setting up a IBOutlet or property. I typical notice all at once and need to add releases for somewhere between 3 and 12 objects. This is a great time to use Ruby to save some typing.

Now there is some debate out there in the Cocoa world about whether or not you need to release objects pointed to from IBOutlets when you use a NIB to initialize. On the iPhone, if you are using an @property(retain), the answer is: “YES, YOU NEED TO RELEASE!!!”. Setting the pointer to nil also makes sense in many situations, but is not needed in the dealloc. The pointer is going to be gone very shortly anyway.

Now, this is a problem that is trivial to solve with Ruby. I want to give a script the declarations from my header file and have it give me back the code I need in my dealloc method. Of course I only want to release objects, so i skip any lines that don’t contain a “*”. If you are using a lot of untyped pointer (id), you may want to add support for that. Thanks to Joe Pecoraro for helping me make this code more rubytastic.

#!/usr/bin/ruby

puts
File.open(ARGV[0]).each do |line|
  line = line.split
  if line[0] == "IBOutlet"
      puts "[#{line[2].tr('*;','')} release];"
  elsif line[1] and line[1].include? "*"
      puts "[#{line[1].tr('*;','')} release];"
  end
end
puts

We put the input data into a file and pass that file name as the first arg to our script. Sample data could be

NSArray *titles;
NSArray *gorillas;
IBOutlet UISearchBar *searchBar;
IBOutlet UISegmentedControl *seg;
IBOutlet UITableView *tView;
BOOL firstAppear;
NSSoupPot *pot;

and we get back

jcannatti@li103-64:~/code/scripts/ruby_scripts$ ./dealloc_generate.rb data

[titles release];
[gorillas release];
[searchBar release];
[seg release];
[tView release];
[pot release];

I know that’s not that much text, but the key here is having a shell open and ready to go at all times. Then this can be a time saver.

 
1 Comment

Posted in General

 

Developing Your Programming Chops: The Way Jazz Cats Would Do It

05 Dec

I’ve been playing music almost as long as I’ve been writing code. I think I wrote my first line of BASIC about 2 years before I got my first drumset. I even spent a number of years studying classical and jazz guitar at the college level. I remember those long days in the Dana School of Music practice rooms. Four hours of practice a day is what the professors expect from you. For me, many of those hours were spent trying to learn to play jazz guitar solos by ear. Slaving away trying to get every note correct, not because I wanted to play those solos for an audience, but because that is how you learn to play like the greats.

Programmers also know that if they want to be good, they have to spend a lot of time at their craft. We tend to be more pragmatic then musicians however. Programmers spend their ‘practice’ time working on open source projects, reading O’Reilly books, or on original applications. What about trying to perfectly copy an application that you love? Sometimes programmers do this, but it usually has a practical reason. They don’t want to pay for a piece of software that they feel is overpriced, so they write it themselves. Or maybe, that software isn’t available for a certain platform that they prefer. And sometimes they even just plain think they can make something better or cheaper and take an existing product’s market.

I’m going to try something different. I am going to copy applications that I like solely for the purpose of building my chops. After the fact maybe I’ll find something useful to do with the code, but it will have no impact on what apps I copy.  The first app on my list is Stackoverflow. I’m going to use Ruby on Rails with jQuery. Again my goal here is not to have a profitable or useful product. It’s just a really good way to learn Rails, jQuery, and CSS. My iPhone development day job doesn’t gain me much experience with these tools, and I would like to get much better with them. I think copying a site like Stackoverflow feature-for-feature is a great way to learn. I’ve already easily doubled my skills in CSS. Although that only means going from about a 2/10 to a 4/10. I’ve got a pretty good clone of the front page.

CSS example

CSS example

We’ll see if when I’m done I regret my decision. Maybe my time would have been better spent fixing that bug in GIMP on OS  X, or starting a company. Who knows?

 
No Comments

Posted in General