From 5ef44a5ccb3bcfc16717fd62519b133c01e2a124 Mon Sep 17 00:00:00 2001
From: Sami Samhuri I'm a Rails newbie and eager to learn. I welcome any suggestions or criticism you have. You can direct them to my inbox or leave me a comment below. It's unlikely that he was surprised at my lengthy response, but I was. I have been known to write him long messages on topics that interest me. However, I've only been learning Rails for two weeks or so. Could I possibly have so much to say about it already? Apparently I do. I assume a pretty basic knowledge of what Rails is, so if you're not familiar with it now's a good time to read something on the official Rails website and watch the infamous 15-minute screencast, where Rails creator, David Heinemeier Hansson, creates a simple blog application. The screencasts are what sparked my curiosity, but they hardly scratch the surface of Rails. After that I spent hours reading whatever I could find about Rails before deciding to take the time to learn it well. As a result, a lot of what you read here will sound familiar if you've read other blogs and articles about Rails. This post wasn't planned so there's no list of references yet. I hope to add some links though so please contact me if any ideas or paraphrasing here is from your site, or if you know who I should give credit to. Rails is like my Black & Decker toolkit. I have a hammer, power screwdriver, tape measure, needle-nose pliers, wire cutters, a level, etc. This is exactly what I need—no more, no less. It helps me get things done quickly and easily that would otherwise be painful and somewhat difficult. I can pick up the tools and use them without much training. Therefore I am instantly productive with them. The kit is suitable for many people who need these things at home, such as myself. Companies build skyscrapers and huge malls and apartments, and they clearly need more powerful tools than I. There are others that just need to drive in a nail to hang a picture, in which case the kit I have is overkill. They're better off just buying and using a single hammer. I happen to fall in the big grey middle chunk, not the other two. I'm a university student. I code because it's satisfying and fun to create software. I do plan on coding for a living when I graduate. I don't work with ancient databases, or create monster sites like Amazon, Google, or Ebay. The last time I started coding a website from scratch I was using PHP, that was around the turn of the millennium. [It was a fan site for a favourite band of mine.] After a year or so I realized I didn't have the time to do it properly (ie. securely and cleanly) if I wanted it to be done relatively soon. A slightly customized MediaWiki promptly took it's place. It did all that I needed quite well, just in a less specific way. The wiki is serving my site extremely well, but there's still that itch to create my own site. I feel if Rails was around back then I may have been able to complete the project in a timely manner. I was also frustrated with PHP. Part of that is likely due to a lack of experience and of formal programming education at that time, but it was still not fun for me. It wasn't until I started learning Rails that I thought "hey, I could create that site pretty quickly using this!" Rails fits my needs like a glove, and this is where it shines. Many professionals are making money creating sites in Rails, so I'm not trying to say it's for amateurs only or something equally silly. Some might say I have merely been swept up in hype and am following the herd. You may be right, and that's okay. I'm going to tell you a story. There was a guy who didn't get one of the oh-so-shiny iPods for a long time, though they looked neat. His discman plays mp3 CDs, and that was good enough for him. The latest iPod, which plays video, was sufficiently cool enough for him to forget that everyone at his school has an iPod and he would be trendy just like them now. Shocker ending: he is I, and I am him. Now I know why everyone has one of those shiny devices. iPods and web frameworks have little in common except that many believe both the iPod and Rails are all hype and flash. I've realized that something creating this kind of buzz may actually just be a good product. I feel that this is the only other thing the iPod and Rails have in common: they are both damn good. Enough about the iPod, everyone hates hearing about it. My goal is to write about the other thing everyone is tired of hearing about. Rails is not magic. There are no exclusive JavaScript libraries or HTML tags. We all have to produce pages that render in the same web browsers. My dad was correct, there is nothing special about my website either. It's more or less a stock Typo website. So what makes developing with Rails different? For me there are four big things that set Rails apart from the alternatives: Now I'm sure you've heard about separating content from design. Rails takes that one step further from just using CSS to style your website. It uses what's known as the MVC paradigm: Model-View-Controller. This is a tried and tested development method. I'd used MVC before in Cocoa programming on Mac OS X, so I was already sold on this point. Of course this is not exclusive to Rails, but it's an integral part of it's design. Rails, and Ruby, both read amazingly like spoken English. This code is more or less straight out of Typo. You define relationships between objects like this: In the Comment model you have: (I snuck in some validations as well) But look how it reads! Read it out loud. I'd bet that my mom would more or less follow this, and she's anything but a programmer. That's not to say programming should be easy for grandma, but code should be easily understood by humans. Let the computer understand things that are natural for me to type, since we're making it understand a common language anyways. Ruby and Ruby on Rails allow and encourage you to write beautiful code. That is so much more important than you may realize, because it leads to many other virtues. Readability is obvious, and hence maintainability. You must read code to understand and modify it. Oh, and happy programmers will be more productive than frustrated programmers. Here's one more life-saver: migrations. Migrations are a way to version your database schema from within Rails. So you have a table, call it Then you run the migration ( Along with the other screencasts is one on migrations featuring none other than David Hansson. You should take a look, it's the third video. To start a rails project you type Rails builds on the unit testing that comes with Ruby. On a larger scale, that means that Rails is unlikely to flop on you because it is regularly tested using the same method. Ruby is unlikely to flop for the same reason. That makes me look good as a programmer. If you code for a living then it's of even more value to you. I don't know why it hurts. Maybe it hurts developers working with other frameworks or languages to see us have it so nice and easy. Rails means I have fun doing web development instead of being frustrated (CSS hacks aside). David Hansson may be right when he said you have to have been soured by Java or PHP to fully appreciate Rails, but that doesn't mean you won't enjoy it if you do like Java or PHP. Justin Gehtland rewrote a Java app using Rails and the number of lines of code of the Rails version was very close to that of the XML configuration for the Java version. Java has strengths, libraries available now seems to be a big one, but it's too big for my needs. If you're like me then maybe you'll enjoy Rails as much as I do. Sort of... there are a few things that it seems standard to include when someone writes about how Rails saved their life and gave them hope again. For completeness sake, I feel compelled to mention some principles common amongst those who develop Rails, and those who develop on Rails. It's entirely likely that there's nothing new for you here unless you're new to Rails or to programming, in which case I encourage you to read on. Rails follows the DRY principle religiously. That is, Don't Repeat Yourself. Like MVC, I was already sold on this. I had previously encountered it in The Pragmatic Programmer. Apart from telling some_model it Rails' developers also have the mantra "convention over configuration", which you can see from the video there. (you did watch it, didn't you? ;) Basically that just means Rails has sane defaults, but is still flexible if you don't like the defaults. You don't have to write even one line of SQL with Rails, but if you need greater control then you can write your own SQL. A standard cliché: it makes the simple things easy and the hard possible. Rails seems to have a level of intelligence which contributes to the wow-factor. After these relationships are defined I can now filter certain negative comments like so: Rails knows to look for the field article_id in the comments table of the database. This is just a convention. You can call it something else but then you have to tell Rails what you like to call it. Rails understands pluralization, which is a detail but it makes everything feel more natural. If you have a Person model then it will know to look for the table named people. I love how I've only been coding in Rails for a week or two and I can do so much already. It's natural, concise and takes care of the inane details. I love how I know that I don't even have to explain that migration example. It's plainly clear what it does to the database. It doesn't take long to get the basics down and once you do it goes fast. P.S. I tried several ways to get the combo-snippets to put the pieces inside the right functions but failed. We'll see tomorrow if Allan (creator of TextMate) has any ideas. UPDATE: I got everything working and it's all packaged up here. There's an installation script this time as well. Thanks to a helpful thread on the TextMate mailing list I have the beginning of a solution to insert text at 2 (or more) locations in a file. I implemented this for a new snippet I was working on for migrations, That's enough introduction, here's the program to do the insertion: Save this as a command in your Rails, or syncPeople on Rails, bundle. The command options should be as follows: The first modification it needs is to get the lines to insert as command line arguments so we can use it for other snippets. Secondly, regardless of the Re-indent pasted text setting the text returned is indented incorrectly. UPDATE: This is obsolete, see this post for a better solution. Duane's comment prompted me to think about how to get the Use MCDT to insert: Then press tab once more after typing the table name to select the code I have this bound to ⌃⌥⌘M because it wasn't in use. If your Control key is to the left the A key it's quite comfortable to hit this combo. Copy the following file into ~/Library/Application Support/TextMate/Bundles/Rails.tmbundle/Macros. This works for the MARC snippet as well. I didn't tell you the whole truth, the macro actually finds the previous occurence of The caveat here is that if there is a If you have XP Home then the best you can do is run this script from your Startup folder (Start -> All Programs -> Startup), but that is not really going to work because eventually Windows will not even let you log in until you activate it. What a P.O.S.Ruby on Rails background
-
Rails through my eyes
-
Web Frameworks and iPods?
-
Why is Rails special?
-
-
MVC 101 (or, Separating data, function, and design)
-
-
-
-
add_product method of the cart model and tell it which product to add. Then the controller takes the appropriate action such as redirecting the user to the shopping cart view.Readability
-
class Article < Content
- has_many :comments, :dependent => true, :order => "created_at ASC"
- has_many :trackbacks, :dependent => true, :order => "created_at ASC"
- has_and_belongs_to_many :categories, :foreign_key => 'article_id'
- has_and_belongs_to_many :tags, :foreign_key => 'article_id'
- belongs_to :user
- ...dependent => true means if an article is deleted, it's comments go with it. Don't worry if you don't understand it all, this is just for you to see some actual Rails code.class Comment < Content
- belongs_to :article
- belongs_to :user
-
- validates_presence_of :author, :body
- validates_against_spamdb :body, :url, :ip
- validates_age_of :article_id
- ...Database Migrations
-
albums, and you want to add the date the album was released. You could modify the database directly, but that's not fun. Even if you only have one server, all your configuration will be in one central place, the app. And Rails doesn't care if you have PostgreSQL, MySQL, or SQLite behind it. You can develop and test on SQLite and deploy on MySQL and the migrations will just work in both environments.class AddDateReleased < ActiveRecord::Migration
- def self.up
- add_column "albums", "date_released", :datetime
- Albums.update_all "date_released = now()"
- end
-
- def self.down
- remove_column "albums", "date_released"
- end
-endrake migrate does that) and boom, your up to date. If you're wondering, the self.down method indeed implies that you can take this the other direction as well. Think rake migrate VERSION=X.Testing so easy it hurts
-
rails project_name and it creates a directory structure with a fresh project in it. This includes a directory appropriately called test which houses unit tests for the project. When you generate models and controllers it creates test stubs for you in that directory. Basically, it makes it so easy to test that you're a fool not to do it. As someone wrote on their site: It means never having to say "I introduced a new bug while fixing another."Wrapping up
-
You're not done, you lied to me!
-
DRY
-
belongs_to :other_model and other_model that it has_many :some_models nothing has jumped out at me which violates this principle. However, I feel that reading a model's code and seeing it's relationships to other models right there is a Good Thing™.Convention over configuration (or, Perceived intelligence)
-
article = Article.find :first
-for comment in article.comments do
- print comment unless comment.downcase == 'you suck!'
-endCode as you learn
-
method(arg1, arg2_)def method(arg1, arg2)
- _
-endrename_column. Since the command is the same in self.up and self.down simply doing a reverse search for rename_column in my hackish macro didn't return the cursor the desired location.#!/usr/bin/env ruby
-def indent(s)
- s =~ /^(\s*)/
- ' ' * $1.length
-end
+up_line = 'rename_column "${1:table}", "${2:column}", "${3:new_name}"$0'
+down_line = "rename_column \"$$1\", \"$$3\", \"$$2\"\n"
-up_line = 'rename_column "${1:table}", "${2:column}", "${3:new_name}"$0'
-down_line = "rename_column \"$$1\", \"$$3\", \"$$2\"\n"
+# find the end of self.down and insert 2nd line
+lines = STDIN.read.to_a.reverse
+ends_seen = 0
+lines.each_with_index do |line, i|
+ ends_seen += 1 if line =~ /^\s*end\b/
+ if ends_seen == 2
+ lines[i..i] = [lines[i], indent(lines[i]) * 2 + down_line]
+ break
+ end
+end
-# find the end of self.down and insert 2nd line
-lines = STDIN.read.to_a.reverse
-ends_seen = 0
-lines.each_with_index do |line, i|
- ends_seen += 1 if line =~ /^\s*end\b/
- if ends_seen == 2
- lines[i..i] = [lines[i], indent(lines[i]) * 2 + down_line]
- break
- end
-end
-
-# return the new text, escaping special chars
-print up_line + lines.reverse.to_s.gsub('[$`\\]', '\\\\\1').gsub('\\$\\$', '$')
-
-
diff --git a/posts/2006/02/textmate-move-selection-to-self-down.md b/posts/2006/02/textmate-move-selection-to-self-down.md
index 0fa85b4..28ecd07 100644
--- a/posts/2006/02/textmate-move-selection-to-self-down.md
+++ b/posts/2006/02/textmate-move-selection-to-self-down.md
@@ -4,29 +4,26 @@ Author: Sami Samhuri
Date: "21st February, 2006"
Timestamp: 2006-02-21T00:26:00-08:00
Tags: [textmate, rails, hacking, hack, macro, rails, textmate]
-Styles: typocode.css
---
⌃W)drop_table and remove_column lines inserted in the right place. I don't think TextMate's snippets are built to do this sort of text manipulation. It would be nicer, but a quick hack will suffice for now.create_table "table" do |t|
+```ruby
+create_table "table" do |t|
-end
-drop_table "table"drop_table "table". I created a macro that cuts the selected text, finds def self.down and pastes the line there. Then it searches for the previous occurence of create_table and moves the cursor to the next line, ready for you to add some columns.(create_table|add_column).create_table or add_column between self.down and the table you just added, it will jump back to the wrong spot. It's still faster than doing it all manually, but should be improved. If you use these exclusively, the order they occur in self.down will be opposite of that in self.up. That means either leaving things backwards or doing the re-ordering manually. =/
+echo $foo->static_fun();
+echo $foo->not_static();
+echo '';
+```
Produces:
-
+```php
class Foo {
public static function static_fun()
{
@@ -29,7 +29,7 @@ class Foo {
}
}
-echo '<pre>';
+echo '';
echo "From Foo:\n";
echo Foo::static_fun();
echo Foo::not_static();
@@ -37,14 +37,14 @@ echo "\n";
echo "From \$foo = new Foo():\n";
$foo = new Foo();
-echo $foo->static_fun();
-echo $foo->not_static();
-echo '</pre>';
-
+```
What the fuck?! http://www.php.net/manual/en/language.oop5.static.php is lying to everyone.
diff --git a/posts/2006/07/late-static-binding.md b/posts/2006/07/late-static-binding.md
index f1fb0ca..032fe45 100644
--- a/posts/2006/07/late-static-binding.md
+++ b/posts/2006/07/late-static-binding.md
@@ -10,8 +10,7 @@ Tags: [php, coding, coding, php]
As colder on ##php (freenode) told me today, class methods in PHP don't have what they call late static binding. What's that? It means that this code:
-
+```php
From Foo:
This is a class method!
This is an instance method!
@@ -52,7 +52,7 @@ This is an instance method!
From $foo = new Foo():
This is a class method!
This is an instance method!
-
-
+```
outputs "I'm a Foo!", instead of "I'm a Bar!". That's not fun.
Using
+```php
class Foo
{
public static function my_method()
@@ -24,15 +23,13 @@ class Bar extends Foo
{}
Bar::my_method();
-
-__CLASS__ in place of get_class() makes zero difference. You end up with proxy methods in each subclass of Foo that pass in the real name of the calling class, which sucks.
-
-
+```
I was told that they had a discussion about this on the internal PHP list, so at least they're thinking about this stuff. Too bad PHP5 doesn't have it. I guess I should just be glad I won't be maintaining this code.
diff --git a/posts/2006/12/coping-with-windows-xp-activiation-on-a-mac.md b/posts/2006/12/coping-with-windows-xp-activiation-on-a-mac.md
index 281e6ba..2815efc 100644
--- a/posts/2006/12/coping-with-windows-xp-activiation-on-a-mac.md
+++ b/posts/2006/12/coping-with-windows-xp-activiation-on-a-mac.md
@@ -28,7 +28,9 @@ If anyone actually knows how to write batch files I'd like to hear any suggestio
You will probably just want to test my method of testing for Parallels and Boot Camp first. The easiest way is to just open a command window and run this command:
- ipconfig /all | find "Parallels"
+```bat
+ipconfig /all | find "Parallels"
+```
If you see a line of output like **"Description . . . . : Parallels Network Adapter"** and you are in Parallels then the test works. If you see no output and you are in Boot Camp then the test works.
@@ -46,8 +48,10 @@ If you're lazy then you can download backup-parallels-wpa.bat
@@ -57,8 +61,10 @@ Download backup-bootcamp-wpa.bat
@@ -72,19 +78,21 @@ If you have XP Pro then you can get it to run using the Group Policy editor. Sav
+```php
class Bar extends Foo
{
public static function my_method()
@@ -40,8 +37,7 @@ class Bar extends Foo
return parent::my_method( get_class() );
}
}
-
-1
-2
-3
-4
-
-
+```ruby
+# extend ActiveRecord::Base with find_or_create and find_or_initialize.
+ActiveRecord::Base.class_eval do
+ include ActiveRecordExtensions
+end
+```
+```ruby
+module ActiveRecordExtensions
+ def self.included(base)
+ base.extend(ClassMethods)
+ end
-# extend ActiveRecord::Base with find_or_create and find_or_initialize.
-ActiveRecord::Base.class_eval do
- include ActiveRecordExtensions
-end1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-16
-17
-18
-19
-20
-21
-22
-23
-24
-25
-26
-27
-28
-29
-30
-31
-32
-33
-34
-35
-36
-37
-38
-39
-40
-41
-
-
+ # call the appropriate ActiveRecord finder method
+ self.send("find_or_#{action}_by_#{attrs.keys.join('_and_')}", *attrs.values)
+ end
+ end
+end
+```
diff --git a/posts/2007/04/funny-how-code-can-be-beautiful.md b/posts/2007/04/funny-how-code-can-be-beautiful.md
index 816b774..c22e9ae 100644
--- a/posts/2007/04/funny-how-code-can-be-beautiful.md
+++ b/posts/2007/04/funny-how-code-can-be-beautiful.md
@@ -8,7 +8,9 @@ Tags: [haskell]
While reading a Haskell tutorial I came across the following code for defining the Fibonacci numbers:
- fib = 1 : 1 : [ a + b | (a, b) <- zip fib (tail fib) ]
+```haskell
+fib = 1 : 1 : [ a + b | (a, b) <- zip fib (tail fib) ]
+```
After reading it a few times and understanding how it works I couldn’t help but think how beautiful it is. I don’t mean that it’s aesthetically pleasing to me; the beautiful part is the meaning and simplicity. Lazy evaluation is sweet.
@@ -24,4 +26,3 @@ Going deeper down the functional rabbit-hole you’ll find things like What the hell are Monads?
* Monads on WikiBooks
* Monads for the Working Haskell Programmer
-
diff --git a/posts/2007/05/a-scheme-parser-in-haskell-part-1.md b/posts/2007/05/a-scheme-parser-in-haskell-part-1.md
index 2d02723..f00f6eb 100644
--- a/posts/2007/05/a-scheme-parser-in-haskell-part-1.md
+++ b/posts/2007/05/a-scheme-parser-in-haskell-part-1.md
@@ -18,9 +18,10 @@ I'm going to explain one of the exercises because converting between the various
Last night I rewrote module ActiveRecordExtensions
- def self.included(base)
- base.extend(ClassMethods)
- end
+ module ClassMethods
+ def find_or_initialize(params)
+ find_or_do('initialize', params)
+ end
- module ClassMethods
- def find_or_initialize(params)
- find_or_do('initialize', params)
- end
-
- def find_or_create(params)
- find_or_do('create', params)
- end
+ def find_or_create(params)
+ find_or_do('create', params)
+ end
private
- # Find a record that matches the attributes given in the +params+ hash, or do +action+
- # to retrieve a new object with the given parameters and return that.
- def find_or_do(action, params)
- # if an id is given just find the record directly
- self.find(params[:id])
+ # Find a record that matches the attributes given in the +params+ hash, or do +action+
+ # to retrieve a new object with the given parameters and return that.
+ def find_or_do(action, params)
+ # if an id is given just find the record directly
+ self.find(params[:id])
- rescue ActiveRecord::RecordNotFound => e
- attrs = {} # hash of attributes passed in params
+ rescue ActiveRecord::RecordNotFound => e
+ attrs = {} # hash of attributes passed in params
- # search for valid attributes in params
- self.column_names.map(&:to_sym).each do |attrib|
- # skip unknown columns, and the id field
- next if params[attrib].nil? || attrib == :id
+ # search for valid attributes in params
+ self.column_names.map(&:to_sym).each do |attrib|
+ # skip unknown columns, and the id field
+ next if params[attrib].nil? || attrib == :id
attrs[attrib] = params[attrib]
- end
+ end
- # no valid params given, return nil
- return nil if attrs.empty?
+ # no valid params given, return nil
+ return nil if attrs.empty?
- # call the appropriate ActiveRecord finder method
- self.send("find_or_#{action}_by_#{attrs.keys.join('_and_')}", *attrs.values)
- end
- end
-endparseNumber using do and >>= (bind) notations (ex. 3.3.1). Here's parseNumber using the liftM method given in the tutorial:
-
+```
Okay that's pretty simple right? Let's break it down, first looking at the right-hand side of the parseNumber :: Parser LispVal
+```haskell
+parseNumber :: Parser LispVal
parseNumber :: liftM (Number . read) $ many1 digit
-$ operator, then the left.
* many1 digit reads as many decimal digits as it can.
@@ -41,24 +42,25 @@ The $ acts similar to a pipe in $FAVOURITE_SHELL, and
So how does a Haskell newbie go about re-writing that using other notations which haven't even been explained in the tutorial? Clearly one must search the web and read as much as they can until they understand enough to figure it out (which is one thing I like about the tutorial). If you're lazy like me, here are 3 equivalent pieces of code for you to chew on. parseNumber's type is Parser LispVal (Parser is a monad).
-
Familiar liftM method:
-
+```haskell
+parseNumber -> liftM (Number . read) $ many1 digit
+```
Using parseNumber -> liftM (Number . read) $ many1 digit
-do notation:
-
+```
If you're thinking "Hey a parseNumber -> do digits <- many1 digit
+```haskell
+parseNumber -> do digits <- many1 digit
return $ (Number . read) digits
-return, I know that one!" then the devious masterminds behind Haskell are certainly laughing evilly right now. return simply wraps up it's argument in a monad of some sort. In this case it's the Parser monad. The return part may seem strange at first. Since many1 digit yields a monad why do we need to wrap anything? The answer is that using <- causes digits to contain a String, stripped out of the monad which resulted from many1 digit. Hence we no longer use liftM to make (Number . read) monads, and instead need to use return to properly wrap it back up in a monad.
In other words liftM eliminates the need to explicitly re-monadize the contents as is necessary using do.
-
Finally, using >>= (bind) notation:
-
+```
At this point I don't think this warrants much of an explanation. The syntactic sugar provided by parseNumber -> many1 digit >>= \digits ->
+```haskell
+parseNumber -> many1 digit >>= \digits ->
return $ (Number . read) digits
-do should be pretty obvious. Just in case it's not, >>= passes the contents of its left argument (a monad) to the function on its right. Once again return is needed to wrap up the result and send it on its way.
When I first read about Haskell I was overwhelmed by not knowing anything, and not being able to apply my previous knowledge of programming to anything in Haskell. One piece of syntax at a time I am slowly able to understand more of the Haskell found in the wild.
diff --git a/posts/2007/05/dumping-objects-to-the-browser-in-rails.md b/posts/2007/05/dumping-objects-to-the-browser-in-rails.md
index db5454a..ac2de53 100644
--- a/posts/2007/05/dumping-objects-to-the-browser-in-rails.md
+++ b/posts/2007/05/dumping-objects-to-the-browser-in-rails.md
@@ -4,32 +4,35 @@ Author: Sami Samhuri
Date: "15th May, 2007"
Timestamp: 2007-05-15T13:38:00-07:00
Tags: [rails]
-Styles: typocode.css
---
Here's an easy way to solve a problem that may have nagged you as it did me. Simply using foo.inspect to dump out some object to the browser dumps one long string which is barely useful except for short strings and the like. The ideal output is already available using the PrettyPrint module so we just need to use it.
-
-Unfortunately typing to quickly debug some possibly large object (or collection) can get old fast so we need a shortcut.
-
+Unfortunately typing <%= PP.pp(@something, '') %>
<pre><%= PP.pp(@something, '') %></pre> to quickly debug some possibly large object (or collection) can get old fast so we need a shortcut.
Taking the definition of Object#pp_s from the extensions project it's trivial to create a helper method to just dump out an object in a reasonable manner.
+**/app/helpers/application_helper.rb**
-def dump(thing)
- s = StringIO.new
- PP.pp(thing, s)
- s.string
-endObject#pp_s so you can use it in your logs or anywhere else you may want to inspect an object. If you do this you probably want to change the dump helper method accordingly in case you decide to change pp_s in the future.
+**lib/local_support/core_ext/object.rb**
-class Object
- def pp_s
- pps = StringIO.new
- PP.pp(self, pps)
- pps.string
- end
-endSymbol#to_proc, which shouldn't need an introduction. If you're using Rails you have this already.
-class Symbol
- # Turns a symbol into a proc.
- #
- # Example:
- # # The same as people.map { |p| p.birthdate }
- # people.map(&:birthdate)
- #
- def to_proc
- Proc.new {|thing, *args| thing.send(self, *args)}
- end
-end
-String#to_proc, which is nearly identical to the Array#to_proc method I previously wrote about.
-class String
- # Turns a string into a proc.
- #
- # Example:
- # # The same as people.map { |p| p.birthdate.year }
- # people.map(&'birthdate.year')
- #
- def to_proc
- Proc.new do |*args|
- split('.').inject(args.shift) do |thing, msg|
- thing = thing.send(msg.to_sym, *args)
- end
- end
- end
-end
-Enumerable#to_proc which returns a proc that passes its parameter through each of its members and collects their results. It's easier to explain by example.
-module Enumerable
- # Effectively treats itself as a list of transformations, and returns a proc
- # which maps values to a list of the results of applying each transformation
- # in that list to the value.
- #
- # Example:
- # # The same as people.map { |p| [p.birthdate, p.email] }
- # people.map(&[:birthdate, :email])
- #
- def to_proc
- @procs ||= map(&:to_proc)
- Proc.new do |thing, *args|
- @procs.map do |proc|
- proc.call(thing, *args)
- end
- end
- end
-endEnumerable#pluck for Ruby in all its glory.
-module Enumerable
- # Use this to pluck values from objects, especially useful for ActiveRecord models.
- # This is analogous to Prototype's Enumerable.pluck method but more powerful.
- #
- # You can pluck values simply, like so:
- # >> people.pluck(:last_name) #=> ['Samhuri', 'Jones', ...]
- #
- # But with Symbol#to_proc defined this is effectively the same as:
- # >> people.map(&:last_name) #=> ['Samhuri', 'Jones', ...]
- #
- # Where pluck's power becomes evident is when you want to do something like:
- # >> people.pluck(:name, :address, :phone)
- # #=> [['Johnny Canuck', '123 Maple Lane', '416-555-124'], ...]
- #
- # Instead of:
- # >> people.map { |p| [p.name, p.address, p.phone] }
- #
- # # map each person to: [person.country.code, person.id]
- # >> people.pluck('country.code', :id)
- # #=> [['US', 1], ['CA', 2], ...]
- #
- def pluck(*args)
- # Thanks to Symbol#to_proc, Enumerable#to_proc and String#to_proc this Just Works(tm)
- map(&args)
- end
-end#to_proc methods so as to work with a standard Ruby while only patching 1 module.
-module Enumerable
- # A version of pluck which doesn't require any to_proc methods.
- def pluck(*args)
- procs = args.map do |msgs|
- # always operate on lists of messages
- if String === msgs
- msgs = msgs.split('.').map {|a| a.to_sym} # allow 'country.code'
- elsif !(Enumerable === msgs)
- msgs = [msgs]
- end
- Proc.new do |orig|
- msgs.inject(orig) { |thing, msg| thing = thing.send(msg) }
- end
- end
+```ruby
+module Enumerable
+ # A version of pluck which doesn't require any to_proc methods.
+ def pluck(*args)
+ procs = args.map do |msgs|
+ # always operate on lists of messages
+ if String === msgs
+ msgs = msgs.split('.').map {|a| a.to_sym} # allow 'country.code'
+ elsif !(Enumerable === msgs)
+ msgs = [msgs]
+ end
+ Proc.new do |orig|
+ msgs.inject(orig) { |thing, msg| thing = thing.send(msg) }
+ end
+ end
- if procs.size == 1
- map(&procs.first)
- else
- map do |thing|
- procs.map { |proc| proc.call(thing) }
- end
- end
- end
-end
+ (= (square y) x))))
+```
This only begs the question.
diff --git a/posts/2007/06/emacs-for-textmate-junkies.md b/posts/2007/06/emacs-for-textmate-junkies.md
index 5c417da..9c3ecc3 100644
--- a/posts/2007/06/emacs-for-textmate-junkies.md
+++ b/posts/2007/06/emacs-for-textmate-junkies.md
@@ -14,76 +14,20 @@ Tags: [emacs, textmate]
Despite my current infatuation with Emacs there are many reasons I started using TextMate, especially little time-savers that are very addictive. I'll talk about one of those features tonight. When you have text selected in TextMate and you hit say the (define (sqrt x)
+```scheme
+(define (sqrt x)
(the y (and (= y 0)
- (= (square y) x))))' (single quote) then TextMate will surround the selected text with single quotes. The same goes for double quotes, parentheses, brackets, and braces. This little trick is one of my favourites so I had to come up with something similar in Emacs. It was easy since a mailing list post has a solution for surrounding the current region with tags, which served as a great starting point.
-
-1
-2
-3
-4
-5
-6
-7
-
-
-
+ (insert "" tag-name ">")))
+```
With a little modification I now have the following in my ~/.emacs file:
-
-(defun surround-region-with-tag (tag-name beg end)
+```lisp
+(defun surround-region-with-tag (tag-name beg end)
(interactive "sTag name: \nr")
(save-excursion
(goto-char beg)
- (insert "<" tag-name ">")
+ (insert "<" tag-name ">")
(goto-char (+ end 2 (length tag-name)))
- (insert "</" tag-name ">")))1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-16
-17
-18
-19
-20
-21
-22
-23
-24
-25
-26
-27
-28
-29
-30
-31
-32
-33
-34
-35
-36
-37
-38
-39
-40
-41
-42
-43
-44
-45
-46
-47
-
-
+(global-set-key "<" 'wrap-region-with-tag-or-insert) ;; I opted not to have a wrap-with-angle-brackets
+```
↓ Download wrap-region.el
diff --git a/posts/2007/06/floating-point-in-elschemo.md b/posts/2007/06/floating-point-in-elschemo.md
index 3ed018d..2a2fe3d 100644
--- a/posts/2007/06/floating-point-in-elschemo.md
+++ b/posts/2007/06/floating-point-in-elschemo.md
@@ -10,24 +10,8 @@ Tags: [elschemo, haskell, scheme]
The first task is extending the ;; help out a TextMate junkie
+```lisp
+;; help out a TextMate junkie
(defun wrap-region (left right beg end)
"Wrap the region in arbitrary text, LEFT goes to the left and RIGHT goes to the right."
@@ -103,7 +47,7 @@ With a little modification I now have the following in my ~/.emacs file:
(interactive)
(if (and mark-active transient-mark-mode)
(call-interactively 'wrap-region-with-tag)
- (insert "<")))
+ (insert "<")))
(defun wrap-region-with-tag (tag beg end)
"Wrap the region in the given HTML/XML tag using `wrap-region'. If any
@@ -111,10 +55,10 @@ attributes are specified then they are only included in the opening tag."
(interactive "*sTag (including attributes): \nr")
(let* ((elems (split-string tag " "))
(tag-name (car elems))
- (right (concat "</" tag-name ">")))
+ (right (concat "" tag-name ">")))
(if (= 1 (length elems))
- (wrap-region (concat "<" tag-name ">") right beg end)
- (wrap-region (concat "<" tag ">") right beg end))))
+ (wrap-region (concat "<" tag-name ">") right beg end)
+ (wrap-region (concat "<" tag ">") right beg end))))
(defun wrap-region-or-insert (left right)
"Wrap the region with `wrap-region' if an active region is marked, otherwise insert LEFT at point."
@@ -129,7 +73,8 @@ attributes are specified then they are only included in the opening tag."
(global-set-key "(" (wrap-region-with-function "(" ")"))
(global-set-key "[" (wrap-region-with-function "[" "]"))
(global-set-key "{" (wrap-region-with-function "{" "}"))
-(global-set-key "<" 'wrap-region-with-tag-or-insert) ;; I opted not to have a wrap-with-angle-bracketsLispVal type to grok floats.
-
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-
-
-
+ | ...
+```
The reason for using the new type LispInt = Integer
+```haskell
+type LispInt = Integer
type LispFloat = Float
-- numeric data types
@@ -41,30 +25,22 @@ data LispVal = Atom String
| Number LispNum
| Char Char
| String String
- | ...LispNum type and not just throwing a new Float Float constructor in there is so that functions can accept and operate on parameters of any supported numeric type. First the floating point numbers need to be parsed. For now I only parse floating point numbers in decimal because the effort to parse other bases is too great for the benefits gained (none, for me).
ElSchemo now parses negative numbers so I'll start with 2 helper functions that are used when parsing both integers and floats:
-
-1
-2
-3
-4
-5
-6
-7
-
-
-
+applySign :: Char -> LispNum -> LispNum
+applySign sign n = if sign == '-' then negate n else n
+```
parseSign :: Parser Char
+```haskell
+parseSign :: Parser Char
parseSign = do try (char '-')
- <|> do optional (char '+')
+ <|> do optional (char '+')
return '+'
-applySign :: Char -> LispNum -> LispNum
-applySign sign n = if sign == '-' then negate n else nparseSign is straightforward as it follows the convention that a literal number is positive unless explicitly marked as negative with a leading minus sign. A leading plus sign is allowed but not required.
@@ -72,94 +48,64 @@ applySign sign n = if sign == '-' then negate n else n
Armed with these 2 functions we can now parse floating point numbers in decimal. Conforming to R5RS an optional #d prefix is allowed.
-
-1
-2
-3
-4
-5
-6
-7
-8
-
-
-
+ where makeFloat whole fract = Float . fst . head . readFloat $ whole ++ "." ++ fract
+```
The first 6 lines should be clear. Line 7 simply applies the parsed sign to the parsed number and returns it, delegating most of the work to parseFloat :: Parser LispVal
+```haskell
+parseFloat :: Parser LispVal
parseFloat = do optional (string "#d")
- sign <- parseSign
- whole <- many1 digit
+ sign <- parseSign
+ whole <- many1 digit
char '.'
- fract <- many1 digit
+ fract <- many1 digit
return . Number $ applySign sign (makeFloat whole fract)
- where makeFloat whole fract = Float . fst . head . readFloat $ whole ++ "." ++ fractmakeFloat. makeFloat in turn delegates the work to the readFloat library function, extracts the result and constructs a LispNum for it.
The last step for parsing is to modify parseExpr to try and parse floats.
-
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-
-
-
+ <|> parseComment
+```
### Displaying the floats ###
-
That's it for parsing, now let's provide a way to display these suckers. -- Integers, floats, characters and atoms can all start with a # so wrap those with try.
+```haskell
+-- Integers, floats, characters and atoms can all start with a # so wrap those with try.
-- (Left factor the grammar in the future)
parseExpr :: Parser LispVal
parseExpr = (try parseFloat)
- <|> (try parseInteger)
- <|> (try parseChar)
- <|> parseAtom
- <|> parseString
- <|> parseQuoted
- <|> do char '('
- x <- (try parseList) <|> parseDottedList
+ <|> (try parseInteger)
+ <|> (try parseChar)
+ <|> parseAtom
+ <|> parseString
+ <|> parseQuoted
+ <|> do char '('
+ x <- (try parseList) <|> parseDottedList
char ')'
return x
- <|> parseCommentLispVal is an instance of show, where show = showVal so showVal is our first stop. Remembering that LispVal now has a single Number constructor we modify it accordingly:
+```haskell
+showVal (Number n) = showNum n
-1
-2
-3
-4
-5
-6
-7
-
-
-
+instance Show LispNum where show = showNum
+```
One last, and certainly not least, step is to modify showVal (Number n) = showNum n
-
-showNum :: LispNum -> String
+showNum :: LispNum -> String
showNum (Integer contents) = show contents
showNum (Float contents) = show contents
-instance Show LispNum where show = showNumeval so that numbers evaluate to themselves.
-
- eval env val@(Number _) = return val
+```haskell
+eval env val@(Number _) = return val
+```
There's a little more housekeeping to be done such as fixing integer?, number?, implementing float? but I will leave those as an exercise to the reader, or just wait until I share the full code. As it stands now floating point numbers can be parsed and displayed. If you fire up the interpreter and type 2.5 or -10.88 they will be understood. Now try adding them:
- (+ 2.5 1.1)
- Invalid type: expected integer, found 2.5
+```scheme
+(+ 2.5 1.1)
+Invalid type: expected integer, found 2.5
+```
Oops, we don't know how to operate on floats yet!
@@ -167,79 +113,8 @@ Oops, we don't know how to operate on floats yet!
Parsing was the easy part. Operating on the new floats is not necessarily difficult, but it was more work than I realized it would be. I don't claim that this is the best or the only way to operate on any LispNum, it's just the way I did it and it seems to work. There's a bunch of boilerplate necessary to make LispNum an instance of the required classes, Eq, Num, Real, and Ord. I don't think I have done this properly but for now it works. What is clearly necessary is the code that operates on different types of numbers. I think I've specified sane semantics for coercion. This will be very handy shortly.
-
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-16
-17
-18
-19
-20
-21
-22
-23
-24
-25
-26
-27
-28
-29
-30
-31
-32
-33
-34
-35
-36
-37
-38
-39
-40
-41
-42
-43
-44
-45
-46
-47
-48
-49
-50
-51
-52
-53
-54
-55
-56
-57
-58
-59
-60
-61
-62
-63
-64
-65
-66
-67
-68
-69
-70
-
-
+lispNumLessThanEq :: LispNum -> LispNum -> Bool
+lispNumLessThanEq (Integer x) (Integer y) = x <= y
+lispNumLessThanEq (Integer x) (Float y) = (fromInteger x) <= y
+lispNumLessThanEq (Float x) (Integer y) = x <= (fromInteger y)
+lispNumLessThanEq (Float x) (Float y) = x <= y
+instance Ord LispNum where (<=) = lispNumLessThanEq
+```
Phew, ok with that out of the way now we can actually extend our operators to work with any type of lispNumEq :: LispNum -> LispNum -> Bool
+```haskell
+lispNumEq :: LispNum -> LispNum -> Bool
lispNumEq (Integer arg1) (Integer arg2) = arg1 == arg2
lispNumEq (Integer arg1) (Float arg2) = (fromInteger arg1) == arg2
lispNumEq (Float arg1) (Float arg2) = arg1 == arg2
@@ -247,35 +122,35 @@ lispNumEq (Float arg1) (Integer arg2) = arg1 == (fromInteger arg2)
instance Eq LispNum where (==) = lispNumEq
-lispNumPlus :: LispNum -> LispNum -> LispNum
+lispNumPlus :: LispNum -> LispNum -> LispNum
lispNumPlus (Integer x) (Integer y) = Integer $ x + y
lispNumPlus (Integer x) (Float y) = Float $ (fromInteger x) + y
lispNumPlus (Float x) (Float y) = Float $ x + y
lispNumPlus (Float x) (Integer y) = Float $ x + (fromInteger y)
-lispNumMinus :: LispNum -> LispNum -> LispNum
+lispNumMinus :: LispNum -> LispNum -> LispNum
lispNumMinus (Integer x) (Integer y) = Integer $ x - y
lispNumMinus (Integer x) (Float y) = Float $ (fromInteger x) - y
lispNumMinus (Float x) (Float y) = Float $ x - y
lispNumMinus (Float x) (Integer y) = Float $ x - (fromInteger y)
-lispNumMult :: LispNum -> LispNum -> LispNum
+lispNumMult :: LispNum -> LispNum -> LispNum
lispNumMult (Integer x) (Integer y) = Integer $ x * y
lispNumMult (Integer x) (Float y) = Float $ (fromInteger x) * y
lispNumMult (Float x) (Float y) = Float $ x * y
lispNumMult (Float x) (Integer y) = Float $ x * (fromInteger y)
-lispNumDiv :: LispNum -> LispNum -> LispNum
+lispNumDiv :: LispNum -> LispNum -> LispNum
lispNumDiv (Integer x) (Integer y) = Integer $ x `div` y
lispNumDiv (Integer x) (Float y) = Float $ (fromInteger x) / y
lispNumDiv (Float x) (Float y) = Float $ x / y
lispNumDiv (Float x) (Integer y) = Float $ x / (fromInteger y)
-lispNumAbs :: LispNum -> LispNum
+lispNumAbs :: LispNum -> LispNum
lispNumAbs (Integer x) = Integer (abs x)
lispNumAbs (Float x) = Float (abs x)
-lispNumSignum :: LispNum -> LispNum
+lispNumSignum :: LispNum -> LispNum
lispNumSignum (Integer x) = Integer (signum x)
lispNumSignum (Float x) = Float (signum x)
@@ -287,50 +162,32 @@ instance Num LispNum where
signum = lispNumSignum
fromInteger x = Integer x
-
-lispNumToRational :: LispNum -> Rational
+lispNumToRational :: LispNum -> Rational
lispNumToRational (Integer x) = toRational x
lispNumToRational (Float x) = toRational x
instance Real LispNum where
toRational = lispNumToRational
-
-lispIntQuotRem :: LispInt -> LispInt -> (LispInt, LispInt)
+lispIntQuotRem :: LispInt -> LispInt -> (LispInt, LispInt)
lispIntQuotRem n d = quotRem n d
-lispIntToInteger :: LispInt -> Integer
+lispIntToInteger :: LispInt -> Integer
lispIntToInteger x = x
-lispNumLessThanEq :: LispNum -> LispNum -> Bool
-lispNumLessThanEq (Integer x) (Integer y) = x <= y
-lispNumLessThanEq (Integer x) (Float y) = (fromInteger x) <= y
-lispNumLessThanEq (Float x) (Integer y) = x <= (fromInteger y)
-lispNumLessThanEq (Float x) (Float y) = x <= y
-
-instance Ord LispNum where (<=) = lispNumLessThanEqLispNum. Our Scheme operators are defined using the functions numericBinop and numBoolBinop. First we'll slightly modify our definition of primitives:
-
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-
-
-
+ (">=", numBoolBinop (>=)),
+ ("<=", numBoolBinop (<=)),
+ ...]
+```
Note that primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
+```haskell
+primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
primitives = [("+", numericBinop (+)),
("-", subtractOp),
("*", numericBinop (*)),
@@ -339,94 +196,57 @@ primitives = [("+", numericBinop (+)),
("quotient", integralBinop quot),
("remainder", integralBinop rem),
("=", numBoolBinop (==)),
- ("<", numBoolBinop (<)),
- (">", numBoolBinop (>)),
+ ("<", numBoolBinop (<)),
+ (">", numBoolBinop (>)),
("/=", numBoolBinop (/=)),
- (">=", numBoolBinop (>=)),
- ("<=", numBoolBinop (<=)),
- ...]mod, quotient, and remainder are only defined for integers and as such use integralBinop, while division (/) is only defined for floating point numbers using floatBinop. subtractOp is different to support unary usage, e.g. (- 4) => -4, but it uses numericBinop internally when more than 1 argument is given. On to the implementation! First extend unpackNum to work with any LispNum, and provide separate unpackInt and unpackFloat functions to handle both kinds of LispNum.
-
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-
-
-
+unpackFloat notFloat = throwError $ TypeMismatch "float" notFloat
+```
The initial work of separating integers and floats into the unpackNum :: LispVal -> ThrowsError LispNum
+```haskell
+unpackNum :: LispVal -> ThrowsError LispNum
unpackNum (Number (Integer n)) = return $ Integer n
unpackNum (Number (Float n)) = return $ Float n
unpackNum notNum = throwError $ TypeMismatch "number" notNum
-unpackInt :: LispVal -> ThrowsError Integer
+unpackInt :: LispVal -> ThrowsError Integer
unpackInt (Number (Integer n)) = return n
unpackInt (List [n]) = unpackInt n
unpackInt notInt = throwError $ TypeMismatch "integer" notInt
-unpackFloat :: LispVal -> ThrowsError Float
+unpackFloat :: LispVal -> ThrowsError Float
unpackFloat (Number (Float f)) = return f
unpackFloat (Number (Integer f)) = return $ fromInteger f
unpackFloat (List [f]) = unpackFloat f
-unpackFloat notFloat = throwError $ TypeMismatch "float" notFloatLispNum abstraction, and the code I said would be handy shortly, are going to be really handy here. There's relatively no change in numericBinop except for the type signature. integralBinop and floatBinop are just specific versions of the same function. I'm sure there's a nice Haskelly way of doing this with less repetition, and I welcome such corrections.
-
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-16
-17
-18
-
-
-
+numBoolBinop :: (LispNum -> LispNum -> Bool) -> [LispVal] -> ThrowsError LispVal
+numBoolBinop op params = boolBinop unpackNum op params
+```
That was a bit of work but now ElSchemo supports floating point numbers, and if you're following along then your Scheme might too if I haven't missed any important details!
-
Next time I'll go over some of the special forms I have added, including short-circuiting numericBinop :: (LispNum -> LispNum -> LispNum) -> [LispVal] -> ThrowsError LispVal
+```haskell
+numericBinop :: (LispNum -> LispNum -> LispNum) -> [LispVal] -> ThrowsError LispVal
numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
-numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op
+numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op
-integralBinop :: (LispInt -> LispInt -> LispInt) -> [LispVal] -> ThrowsError LispVal
+integralBinop :: (LispInt -> LispInt -> LispInt) -> [LispVal] -> ThrowsError LispVal
integralBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
-integralBinop op params = mapM unpackInt params >>= return . Number . Integer . foldl1 op
+integralBinop op params = mapM unpackInt params >>= return . Number . Integer . foldl1 op
-floatBinop :: (LispFloat -> LispFloat -> LispFloat) -> [LispVal] -> ThrowsError LispVal
+floatBinop :: (LispFloat -> LispFloat -> LispFloat) -> [LispVal] -> ThrowsError LispVal
floatBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
-floatBinop op params = mapM unpackFloat params >>= return . Number . Float . foldl1 op
+floatBinop op params = mapM unpackFloat params >>= return . Number . Float . foldl1 op
-subtractOp :: [LispVal] -> ThrowsError LispVal
-subtractOp num@[_] = unpackNum (head num) >>= return . Number . negate
+subtractOp :: [LispVal] -> ThrowsError LispVal
+subtractOp num@[_] = unpackNum (head num) >>= return . Number . negate
subtractOp params = numericBinop (-) params
-numBoolBinop :: (LispNum -> LispNum -> Bool) -> [LispVal] -> ThrowsError LispVal
-numBoolBinop op params = boolBinop unpackNum op paramsand and or forms and the full repetoire of let, let*, and letrec. Stay tuned!
-
diff --git a/posts/2007/06/more-scheming-with-haskell.md b/posts/2007/06/more-scheming-with-haskell.md
index 248b82b..fc3095a 100644
--- a/posts/2007/06/more-scheming-with-haskell.md
+++ b/posts/2007/06/more-scheming-with-haskell.md
@@ -14,11 +14,14 @@ It's been a little while since I wrote about Haskell and the R5RS compliant numbers, which is exercise 3.3.4 if you're following along the tutorial. Only integers in binary, octal, decimal, and hexadecimal are parsed right now. The syntaxes for those are #b101010, #o52, 42 (or #d42), and #x2a, respectively. To parse these we use the readOct, readDec, readHex, and readInt functions provided by the Numeric module, and import them thusly:
- import Numeric (readOct, readDec, readHex, readInt)
+```haskell
+import Numeric (readOct, readDec, readHex, readInt)
+```
In order to parse binary digits we need to write a few short functions to help us out. For some reason I couldn't find binDigit, isBinDigit and readBin in their respective modules but luckily they're trivial to implement. The first two are self-explanatory, as is the third if you look at the implementation of its relatives for larger bases. In a nutshell readBin says to: "read an integer in base 2, validating digits with isBinDigit."
-
+readBin = readInt 2 isBinDigit digitToInt
+```
The next step is to augment -- parse a binary digit, analagous to decDigit, octDigit, hexDigit
+```haskell
+-- parse a binary digit, analagous to decDigit, octDigit, hexDigit
binDigit :: Parser Char
binDigit = oneOf "01"
@@ -28,24 +31,30 @@ isBinDigit c = (c == '0' || c == '1')
-- analogous to readDec, readOct, readHex
readBin :: (Integral a) = ReadS a
-readBin = readInt 2 isBinDigit digitToIntparseNumber so that it can handle R5RS numbers in addition to regular decimal numbers. To refresh, the tutorial's parseNumber function looks like this:
- parseNumber :: Parser LispVal
- parseNumber = liftM (Number . read) $ many1 digit
+```haskell
+parseNumber :: Parser LispVal
+parseNumber = liftM (Number . read) $ many1 digit
+```
Three more lines in this function will give us a decent starting point:
- parseNumber = do char '#'
- base <- oneOf "bdox"
- parseDigits base
+```haskell
+parseNumber = do char '#'
+ base <- oneOf "bdox"
+ parseDigits base
+```
Translation: First look for an R5RS style base, and if found call parseDigits with the given base to do the dirty work. If that fails then fall back to parsing a boring old string of decimal digits.
That brings us to actually parsing the numbers. parseDigits is simple, but there might be a more Haskell-y way of doing this.
-
+```
The trickiest part of all this was figuring out how to use the various -- Parse a string of digits in the given base.
+```haskell
+-- Parse a string of digits in the given base.
parseDigits :: Char - Parser LispVal
parseDigits base = many1 d >>= return
where d = case base of
@@ -53,7 +62,7 @@ parseDigits base = many1 d >>= return
'd' -> digit
'o' -> octDigit
'x' -> hexDigit
-readFoo functions properly. They return a list of pairs so head grabs the first pair and fst grabs the first element of the pair. Once I had that straight it was smooth sailing. Having done this, parsing R5RS characters (#\a, #\Z, #\?, ...) is a breeze so I won't bore you with that.
@@ -61,27 +70,17 @@ The trickiest part of all this was figuring out how to use the various rea
It still takes me some time to knit together meaningful Haskell statements. Tonight I spent said time cobbling together an implementation of cond as a new special form. Have a look at the code. The explanation follows.
-
-1
-2
-3
-4
-5
-6
-7
-8
-9
-
-
-
+ Bool False -> case rest of
+ [] -> return $ List []
+ _ -> eval env $ List (Atom "cond" : rest)
+ _ -> liftM last $ mapM (eval env) conseq
+```
* __Lines 1-2:__ Handle eval env (List (Atom "cond" : List (Atom "else" : exprs) : [])) =
+```haskell
+eval env (List (Atom "cond" : List (Atom "else" : exprs) : [])) =
liftM last $ mapM (eval env) exprs
eval env (List (Atom "cond" : List (pred : conseq) : rest)) =
- do result <- eval env $ pred
+ do result <- eval env $ pred
case result of
- Bool False -> case rest of
- [] -> return $ List []
- _ -> eval env $ List (Atom "cond" : rest)
- _ -> liftM last $ mapM (eval env) conseqelse clauses by evaluating the given expression(s), returning the last result. It must come first or it's overlapped by the next pattern.
* __Line 3:__ Evaluate a cond by splitting the first condition into predicate and consequence, tuck the remaining conditions into rest for later.
@@ -93,4 +92,3 @@ eval env (List (Atom "cond" : List (pred : conseq) : rest)) =
* __Line 9:__ Anything other than #f is considered true and causes conseq to be evaluated and returned. Like else, conseq can be a sequence of expressions.
So far my Scheme weighs in at 621 lines, 200 more than the tutorial's final code listing. Hopefully I'll keep adding things on my TODO list and it will grow a little bit more. Now that I have cond it will be more fun to expand my stdlib.scm as well.
-
diff --git a/posts/2007/06/so-long-typo-and-thanks-for-all-the-timeouts.md b/posts/2007/06/so-long-typo-and-thanks-for-all-the-timeouts.md
index 08a5559..e298772 100644
--- a/posts/2007/06/so-long-typo-and-thanks-for-all-the-timeouts.md
+++ b/posts/2007/06/so-long-typo-and-thanks-for-all-the-timeouts.md
@@ -12,22 +12,15 @@ Recently I had looked at converting Typo to Mephisto and it seemed pretty painle
After running that code snippet to fix my tags, I decided to completely ditch categories in favour of tags. I tagged each new Mephisto article with a tag for each Typo category it had previously belonged to. I fired up RAILS_ENV=production script/console and typed something similar to the following:
-1
-2
-3
-4
-5
-6
-7
-
-
-
+```ruby
+require 'converters/base'
+require 'converters/typo'
+articles = Typo::Article.find(:all).map {|a| [a, Article.find_by_permalink(a.permalink)] }
+articles.each do |ta, ma|
+ next if ma.nil?
+ ma.tags << Tag.find_or_create(ta.categories.map(&:name))
+end
+```
When I say something similar I mean exactly that. I just typed that from memory so it may not work, or even be syntactically correct. If any permalinks changed then you'll have to manually add new tags corresponding to old Typo categories. The only case where this bit me was when I had edited the title of an article, in which case the new Mephisto permalink matched the new title while the Typo permalink matched the initial title, whatever it was.
diff --git a/posts/2007/06/testspec-on-rails-declared-awesome-just-one-catch.md b/posts/2007/06/testspec-on-rails-declared-awesome-just-one-catch.md
index f2479d0..92e538b 100644
--- a/posts/2007/06/testspec-on-rails-declared-awesome-just-one-catch.md
+++ b/posts/2007/06/testspec-on-rails-declared-awesome-just-one-catch.md
@@ -10,79 +10,47 @@ This last week I've been getting to know
-
-require 'converters/base'
-require 'converters/typo'
-articles = Typo::Article.find(:all).map {|a| [a, Article.find_by_permalink(a.permalink)] }
-articles.each do |ta, ma|
- next if ma.nil?
- ma.tags << Tag.find_or_create(ta.categories.map(&:name))
-end
-
+```ruby
+use_controller :foo
+```
and can be placed in the use_controller :foosetup method, like so:
+```ruby
+# in test/functional/sessions_controller_test.rb
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-14
-15
-
-
-
+ end
+end
+```
This is great and the test will work. But let's say that I have another controller that guests can access:
+```ruby
+# in test/functional/foo_controller_test.rb
-# in test/functional/sessions_controller_test.rb
+context "A guest" do
+ fixtures :users
-context "A guest" do
- fixtures :users
+ setup do
+ use_controller :sessions
+ end
- setup do
- use_controller :sessions
- end
-
- specify "can login" do
- post :create, :username => 'sjs', :password => 'blah'
- response.should.redirect_to user_url(users(:sjs))
+ specify "can login" do
+ post :create, :username => 'sjs', :password => 'blah'
+ response.should.redirect_to user_url(users(:sjs))
...
- end
-end1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-13
-
-
-
+ end
+end
+```
This test will pass on its own as well, which is what really tripped me up. When I ran my tests individually as I wrote them, they passed. When I ran # in test/functional/foo_controller_test.rb
+context "A guest" do
+ setup do
+ use_controller :foo
+ end
-context "A guest" do
- setup do
- use_controller :foo
- end
-
- specify "can do foo stuff" do
- get :fooriffic
- status.should.be :success
+ specify "can do foo stuff" do
+ get :fooriffic
+ status.should.be :success
...
- end
-endrake test:functionals this morning and saw over a dozen failures and errors I was pretty alarmed. Then I looked at the errors and was thoroughly confused. Of course the action fooriffic can't be found in SessionsController, it lives in FooController and that's the controller I said to use! What gives?!
diff --git a/posts/2007/08/elschemo-boolean-logic-and-branching.md b/posts/2007/08/elschemo-boolean-logic-and-branching.md
index 0312f41..39fdbe5 100644
--- a/posts/2007/08/elschemo-boolean-logic-and-branching.md
+++ b/posts/2007/08/elschemo-boolean-logic-and-branching.md
@@ -16,7 +16,6 @@ that means the code here is for me to get some feedback as much
as to show others how to do this kind of stuff. This may not be too
interesting if you haven't at least browsed the tutorial.
-
I'm going to cover 3 new special forms: and, or, and cond. I
promised to cover the let family of special forms this time around
but methinks this is long enough as it is. My sincere apologies if
@@ -45,25 +44,16 @@ concise language. My explanations may be redundant because of this.
### lispAnd ###
-
-1
-2
-3
-4
-5
-6
-7
-8
-
-
-
+ Bool False -> return result
+ _ -> lispAnd env rest
+```
Starting with the trivial case, lispAnd :: Env -> [LispVal] -> IOThrowsError LispVal
+```haskell
+lispAnd :: Env -> [LispVal] -> IOThrowsError LispVal
lispAnd env [] = return $ Bool True
lispAnd env [pred] = eval env pred
lispAnd env (pred:rest) = do
- result <- eval env pred
+ result <- eval env pred
case result of
- Bool False -> return result
- _ -> lispAnd env restand returns #t with zero
arguments.
@@ -84,25 +74,16 @@ just complicates things but it's a viable solution.
Predictably this is quite similar to lispAnd.
-
-1
-2
-3
-4
-5
-6
-7
-8
-
-
-
+ Bool False -> lispOr env rest
+ _ -> return result
+```
With no arguments lispOr :: Env -> [LispVal] -> IOThrowsError LispVal
+```haskell
+lispOr :: Env -> [LispVal] -> IOThrowsError LispVal
lispOr env [] = return $ Bool False
lispOr env [pred] = eval env pred
lispOr env (pred:rest) = do
- result <- eval env pred
+ result <- eval env pred
case result of
- Bool False -> lispOr env rest
- _ -> return resultlispOr returns #f, and with one argument it
evaluates and returns the result.
@@ -117,33 +98,23 @@ First let me define a convenience function that I have added to
ElSchemo. It maps a list of expressions to their values by evaluating
each one in the given environment.
-
-1
-2
-
-
-
+```haskell
+evalExprs :: Env -> [LispVal] -> IOThrowsError [LispVal]
+evalExprs env exprs = mapM (eval env) exprs
+```
### lispCond ###
Again, evalExprs :: Env -> [LispVal] -> IOThrowsError [LispVal]
-evalExprs env exprs = mapM (eval env) exprslispCond has the same type as eval.
-
-1
-2
-3
-4
-5
-6
-
-
-
+ Bool False -> if null rest then return result else lispCond env rest
+ _ -> liftM last $ evalExprs env conseq
+```
Unlike Lisp – which uses a predicate of lispCond :: Env -> [LispVal] -> IOThrowsError LispVal
+```haskell
+lispCond :: Env -> [LispVal] -> IOThrowsError LispVal
lispCond env (List (pred:conseq) : rest) = do
- result <- eval env pred
+ result <- eval env pred
case result of
- Bool False -> if null rest then return result else lispCond env rest
- _ -> liftM last $ evalExprs env conseqT (true) – Scheme uses a
predicate of else to trigger the default branch. When the pattern
@@ -164,15 +135,11 @@ expressions and return the value of the last one.
Now all that's left is to hook up the new functions in eval.
-
-1
-2
-3
-
-
-
+eval env (List (Atom "cond" : params)) = lispCond env params
+```
You could, of course, throw the entire definitions in eval env (List (Atom "and" : params)) = lispAnd env params
+```haskell
+eval env (List (Atom "and" : params)) = lispAnd env params
eval env (List (Atom "or" : params)) = lispOr env params
-eval env (List (Atom "cond" : params)) = lispCond env paramseval itself but eval is big
enough for me as it is. YMMV.
diff --git a/posts/2007/10/gtkpod-in-gutsy-got-you-groaning.md b/posts/2007/10/gtkpod-in-gutsy-got-you-groaning.md
index 5d833fb..b31a361 100644
--- a/posts/2007/10/gtkpod-in-gutsy-got-you-groaning.md
+++ b/posts/2007/10/gtkpod-in-gutsy-got-you-groaning.md
@@ -21,21 +21,8 @@ Now that you know what to do I'll give you what you probably wanted at the begin
↓ gtkpod-aac-fix.sh
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
-
-
-
+rm -rf /tmp/gtkpod-fix
+```
diff --git a/posts/2008/03/project-euler-code-repo-in-arc.md b/posts/2008/03/project-euler-code-repo-in-arc.md
index 985af0f..fa62e2a 100644
--- a/posts/2008/03/project-euler-code-repo-in-arc.md
+++ b/posts/2008/03/project-euler-code-repo-in-arc.md
@@ -8,10 +8,10 @@ Tags: [arc, project euler]
Release early and often. This is a code repo web app for solutions to Project Euler problems. You can only see your own solutions so it's not that exciting yet (but it scratches my itch... once it highlights syntax). You can try it out or download the source. You'll need an up-to-date copy of Anarki to untar the source in. Just run arc.sh then enter this at the REPL:
-
-mkdir /tmp/gtkpod-fix
+```shell
+mkdir /tmp/gtkpod-fix
cd /tmp/gtkpod-fix
wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmp4v2-0_1.5.0.1-0.3_amd64.deb
wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmp4v2-dev_1.5.0.1-0.3_amd64.deb
@@ -44,6 +31,7 @@ wget http://ftp.uni-kl.de/debian-multimedia/pool/main/libm/libmpeg4ip/libmpeg4ip
for f in *.deb; do sudo gdebi -n "$f"; done
svn co https://gtkpod.svn.sourceforge.net/svnroot/gtkpod/gtkpod/trunk gtkpod
cd gtkpod
-./autogen.sh --with-mp4v2 && make && sudo make install
+./autogen.sh --with-mp4v2 && make && sudo make install
cd
-rm -rf /tmp/gtkpod-fix
+```lisp
+arc> (load "euler.arc")
+arc> (esv)
+```
That will setup the web server on port 3141. If you want a different port then run arc> (load "euler.arc")
-arc> (esv)
-(esv 25) (just to mess with 'em).
diff --git a/posts/2010/01/basics-of-the-mach-o-file-format.md b/posts/2010/01/basics-of-the-mach-o-file-format.md
index bf9bcc2..f5b1394 100644
--- a/posts/2010/01/basics-of-the-mach-o-file-format.md
+++ b/posts/2010/01/basics-of-the-mach-o-file-format.md
@@ -45,17 +45,15 @@ blob of machine code. That blob could be described by a single
section named \_\_text, inside a single nameless segment. Here's a
diagram showing the layout of such a file:
-
+```markdown
,---------------------------,
Header | Mach header |
| Segment 1 |
| Section 1 (__text) | --,
|---------------------------| |
- Data | blob | <-'
+ Data | blob | <-'
'---------------------------'
-
-
+```
Segments, or segment commands, specify where in memory the @@ -92,7 +89,6 @@ be easy enough to follow.
-All sections within a segment are described one after the other @@ -115,7 +111,6 @@ two underscores, e.g. \_\_bss or \_\_text
-As much of the Mach-O format as we need is defined in @@ -126,7 +121,6 @@ constants as well.
I'll cover symbol tables and relocation tables in my next post.
-To see the segments and sections of an object file, run @@ -145,7 +139,6 @@ also disassemble the \_\_text section with
You'll get to know otool quite well if you work with Mach-O.
-That was probably a lot to digest, and to make real sense of it you diff --git a/posts/2010/11/37signals-chalk-dissected.md b/posts/2010/11/37signals-chalk-dissected.md index 474447e..3c74a67 100644 --- a/posts/2010/11/37signals-chalk-dissected.md +++ b/posts/2010/11/37signals-chalk-dissected.md @@ -14,7 +14,8 @@ Tags: [37signals, chalk, ipad, javascript, web, html, css, zepto.js]
The manifest is a nice summary of the contents, and allows browsers to cache the app for offline use. Combine this with mobile Safari's "Add to Home Screen" button and you have yourself a free chalkboard app that works offline.
-CACHE MANIFEST
+```conf
+CACHE MANIFEST
/
/zepto.min.js
@@ -26,7 +27,7 @@ Tags: [37signals, chalk, ipad, javascript, web, html, css, zepto.js]
/images/chalk-tile-red.png
/images/chalk-tile-white.png
/stylesheets/chalk.css
-
+```
Not much there, just 10 requests to fetch the whole thing. 11 including the manifest. In we go.
@@ -170,7 +171,6 @@ chalk-sprites.png-
When the light switch is touched (or clicked) the shade class on the body element is toggled. Nothing to it.
diff --git a/posts/2013/09/linky.md b/posts/2013/09/linky.md index 5d49af3..41b5ae4 100644 --- a/posts/2013/09/linky.md +++ b/posts/2013/09/linky.md @@ -35,17 +35,23 @@ Yup, that is a lot of moving parts. It is rather elegant in a [Unixy way](http:/ For example, the following lines would be created in a file at `~/Dropbox/Linky/Ruxton/