Week 3 Day 1 – Getting started in Prolog

After all my difficulties getting Prolog installed on OSX, i set up a virtual machine with Ubuntu and got it installed straight away, no problem!

sudo apt-get install gprolog

So i think i will be doing my prolog learning in Ubuntu! :)

Yesterday was nice for me, but i don’t think i’ve had my Prolog Epiphany yet! In the exercises, the hardest thing was thinking of books, authors and musicians! My mind just went blank! :)

I set up a couple of knowledge bases, one of which was about musicians, instruments and genres. I set up a few facts about things i know. I made a rule for finding musicians who play guitar, and then a rule to connect genres and instruments, via the musicians. After that i could compile the world and query it in a few different ways.

If i’m honest, it really felt a bit like joining SQL tables, and didn’t feel very innovative. I’m looking forward to getting deeper into prolog and learning a lot more today :)

Week 3 – Installing Prolog in OSX

It’s fair to say, installing Prolog in OSX is a tad tricky.

I tried installing from homebrew.

$ brew search prolog
gnu-prolog  swi-prolog

I first tried gnu-prolog but it seems the version it tries to fetch no longer exists.

A quick look on wikipedia told me that there’s not much difference between gnu-prolog and swi-prolog so i thought i’d give the latter a try. However, that one stalls on “make check” and never seems to get to the end.

So then i thought i’d try the .dmg installer found on gprolog.org. All seemed well until i tried loading up a prolog file:

$ /opt/local/bin/gprolog
GNU Prolog 1.3.1
By Daniel Diaz
Copyright (C) 1999-2009 Daniel Diaz
| ?- ['friends'].
uncaught exception: error(system_error('error trying to execute pl2wam (maybe not found)'),consult/1)

Sooooo … i give up. Now i am downloading Ubuntu which i’m going to install into a virtual machine. I’ve heard it’s a lot easier to install for Ubuntu.

If anyone knows how to install Prolog for OSX please comment below for others’ benefit!

Investigations into Io Concurrency

After yesterday’s very enjoyable Code Retreat in London, i went with Matt Pep to visit Hack Space where we worked together on some Io.

I confess, i haven’t quite finished Day 2′s exercises, but i was anxious to get on and try some of the concurrency stuff. We discovered a couple of interesting things by playing around with it.

Waiting for asynchronous processes

If you start an asynchronous message but don’t add a ‘wait’, the process stays on hold until another Io process starts up. For example:

Io> slower := Object clone
Io> faster := Object clone
Io> slower start := method(wait(2); writeln("slowly ", Date now))
Io> faster start := method(wait(1); writeln("quickly ", Date now))

I’ve added timestamps to the example because it helps to see what is happening.

slower @@start; faster @@start
==> nil
Io> Date now
==> 2011-06-26 12:33:30 BST
Io> wait(3)
quickly 2011-06-26 12:33:34 BST
slowly 2011-06-26 12:33:35 BST
==> nil

I started both slower and faster asynchronously but didn’t wait for them to finish. I checked the current date and time for reference. Then I did a wait(3). At that point Io was in control again and could run the asynchronous processes. The timestamp shows that they didn’t run until the wait had begun.

I wonder, is there a way of detecting whether there are asynchronous processes still waiting to be run?

Actors do one thing at a time

Although you can run start on the objects slower and faster together in parallel, you can’t run two processes on the same object asynchronously. See what happens if we try:

Io> slower @@start; slower @@start; wait(5)
slowly 2011-06-26 12:35:12 BST
slowly 2011-06-26 12:35:14 BST
==> nil

I kind of expected those to come out at the same time, but no, it waits for the method to finish before running it again. I checked and the same thing is true with two different methods. It seems that an object does not run two methods simultaneously.

This is because the object has become an actor, and an actor manages its own resources. I suspect this is probably part of Io’s strategy for avoiding race conditions.

Futures

The concept of futures excited me. It conjured an impression that you’d be able to calculate multiple versions of possible futures … but unfortunately it’s not that exciting.

It seems that a future result is one that may not yet be known. But it doesn’t hold up your program while waiting for the answer. You can store the future answer and move on. Only when you actually try to use it will your program block until it’s available.

Calculating futures seems to follow the same restrictions as the other asynchronous actor processes, in that one object can only do one thing at a time. But two objects can calculate future results concurrently.

Exercises

Ahhh, we didn’t get that far! I hope i’ll be able to do a bit before the skype call today! :)

An Io testing framework

I couldn’t go on for much longer in Io without somehow testing my code. I’m okay with printing out results for a little while, but as soon as i come to refactoring my code i feel the need to assert somehow the results i’m expecting.

I had a nice chat with Matt Pep about it and tried a few things before i came to the idea of adding a shouldEqual slot on Object so that anything can assert equality.

Object shouldEqual := method(expected,
  if(self == expected,
    "." print,
    ("Expected " .. self .. " to equal " .. expected) println
  )
)

This means i can do a few things like this:

myList := List2d clone
myList dim(3, 5)
myList items size shouldEqual(5)

And things like this:

myList set(2, 3, "Middle")
myList get(2, 3) shouldEqual("Middle")

The only question i have now is: how do i take that assertEqual slot definition out of this file and into a file of its own that i can include everywhere from now on?

I’d like to do something like:

require('testFramework.io')

How would you do such a thing in Io?

I’m afraid i still haven’t finished Day 2′s exercises yet! I must move on to Day 3 tomorrow …! :)

Update

Susan Potter has found the answer! I will try this later: Io’s “require”

Week 2 Day 2 – Io craziness!

Io, you mad sexy beast! What kind of craziness is going on here?!

You don’t hide any secrets, do you? I can see all the operators by typing OperatorTable. I see their order of precedence. I can add an operator anywhere i like!

But i’m afraid i’m lost with your message targets and receivers. I’m looking at the example in the book but i’m really not sure what it’s getting at. I think i’m going to have to be guided to try my own example that needs message reflection before i really get this.

Still, cool that i can can implement an ‘unless’ … i see why they say that everything in Io is a message, even things that look like keywords.

Ah, i understand object reflection much more easily. Nice bit of recursion going on there, going up through the prototype hierarchy.


Well, it’s fair to say that day 2 is really stretching me. I spent ages on the fibonacci calculator last night, and still wasn’t happy with my output. I did a recursive calculator which i understood well but it was slow. I then did an iterative calculator which i couldn’t comprehend so well but at least it was faster. I wanted to do some clever algorithm using Phi, but i was too tired!

Tonight i got a bit further. I was stuck by the division by zero problem until i realised that you can use getSlot(“/”) to pull out the current functionality to save for later.

Adding up all the numbers in a 2D array was nice. I first did it as a stand-alone method, like this:

sum2d := method(array,
  total := 0
  array foreach(i, innerArray, total = total + innerArray sum)
  total
)

sum2d(array)

I later had the idea of adding a sum2d slot on the List prototype, like this:

List sum2d := method(
  total := 0
  self foreach(i, innerArray, total = total + innerArray sum)
  total
)

array sum2d

I got the idea from the myAverage slot exercise, which i also enjoyed. I found it quite fascinating that you can extend List so easily like this:

List myAverage := method(
  self sum / self size
)

Later on i went into more detail so as to perform an average only on numeric values in the list:

List myAverage := method(
  sum := 0
  size := 0
  self foreach(i, value,
    if(value type == "Number", sum = sum + value; size = size + 1)
  )
  if(size == 0, return 0)
  sum / size
)

I was very pleased to learn today that, like Ruby, Io has a return option to get out of a method early. That saves a lot of code.

I’m really liking what i’ve seen so far of Io. The hardest thing is getting to know the syntax and idioms.

I still have more to do on Day 2, but that’ll do for tonight!

Update

P.S. Tomorrow i want to make a simple testing framework. I want to be able to do this:

list(1, 2, "only", "average", "numbers", 3) myAverage should == 2

With what i’ve learned so far in Io i think i can do it.

Week 2 Day 1 – Dipping my toe into Io

Today i started to learn a new programming language, for the first time since trying out Lisp several months ago. Here are my first thoughts upon encountering Io.

My initial reactions

Reading a book doesn’t tell you much. I read the chapter twice before i actually tried it out, and doing feels so different from reading. Something about seeing it produce results before your very eyes feels thoroughly enlightening!

I like the space between the receiver and message. It’s so readable. “Vehicle type” and “Vehicle description” are just natural language, you’d hardly think it was code at all!

I don’t much like the concept of the Lobby. It’s like everything is just hanging around there, chilling out, doing nothing. Don’t you guys have someplace to be?! I suppose every language has to keep its objects somewhere – the difference with Io is we get to find them all in one place.

Really understanding prototypes

When i tried out the proto method i think i properly GOT IT. Seeing those hex identifiers really proved to me that i didn’t clone my ferrari from some abstract Car concept. I cloned an actual Car. THE Car, in fact.

Io> ferrari proto
==>  Car_0x1002a6be0:
  drive            = method(...)
  type             = "Car"

Io> Car
==>  Car_0x1002a6be0:
  drive            = method(...)
  type             = "Car"

Io> Car proto
==>  Vehicle_0x1003d9090:
  description      = "Something to take you far away"
  type             = "Vehicle"

Creating a singleton

Could it possibly be any easier to create a singleton?!

Io> Highlander clone = Highlander
==>  Highlander_0x1005ae7f0:
  clone            = Highlander_0x1005ae7f0
  type             = "Highlander"

“Highlander, your clone method returns Highlander.” — “Right you are!”

Io typing

I would say that Io is strongly typed. It will not let me add together a Number and a Sequence (Sequence seems to be what Io calls a string)

Io> 1 + "2"

  Exception: argument 0 to method '+' must be a Number, not a 'Sequence'
  ---------
  message '+' in 'Command Line' on line 1

However, like Ruby, some strings can be converted to numbers:

Io> 1 + "2" asNumber
==> 3

So, even though Io might have guessed what i meant by 1 + “2″ it’s not going to just do it for me unless i ask nicely!

The typing is dynamic, meaning it is figured out at runtime, as demonstrated by this test:

Io> Tester := Object clone
==>  Tester_0x100532ad0:
  type             = "Tester"

Io> Tester test := method(1 + "2")
==> method(
    1 + "2"
)

Io> Tester test

  Exception: argument 0 to method '+' must be a Number, not a 'Sequence'
  ---------
  +                                   Command Line 1
  Tester test                          Command Line 1

Other discoveries

Here is a useful thing:

Io> Object slotNames sort
==> list(, !=, -, .., <, , >=, ?, @, @@, actorProcessQueue, actorRun, ancestorWithSlot, ancestors, and, appendProto, ...)

I am not sure of the distinction between a Sequence and a String. It appears that a Sequence is a String.

Io> "hello" type
==> Sequence
Io> "hello" isKindOf(Sequence)
==> true
Io> "hello" isKindOf(String)
==> true

You can change an object’s prototype and all of a sudden it won’t be able to respond to slots anymore:

Io> Vehicle := Object clone
==>  Vehicle_0x1003d94b0:
  type             = "Vehicle"

Io> Vehicle description := "Something to take you far away"
==> Something to take you far away

Io> Car := Vehicle clone
==>  Car_0x1004ed400:
  type             = "Car"

Io> Car description
==> Something to take you far away

Io> Car setProto(Object)
==>  Car_0x1004ed400:
  type             = "Car"

Io> Car description

  Exception: Car does not respond to 'description'
  ---------
  Car description                      Command Line 1

I found that interesting!

I think i’m going to like Io! :)

Ruby Classes and Superclasses

An interesting question came up in this week’s Seven Languages in Seven Weeks skype call. We initially thought it might be a difference between versions of Ruby, but having looked more closely, i don’t think it is. Both 1.8.7 and 1.9.2 behave in this slightly odd way.

For reference, we are talking about Figure 2.1: Ruby Metamodel on page 26.

As we all now know, 4 is an object.

> 4.class
 => Fixnum

Fixnum inherits from Integer which inherits from Numeric.

> Fixnum.superclass
 => Integer
> Integer.superclass
 => Numeric

Each of Fixnum, Integer and Numeric are of class Class.

> [Fixnum, Integer, Numeric].map(&:class)
 => [Class, Class, Class]

The superclass of Numeric is Object.

> Numeric.superclass
 => Object

But the superclass of Class goes to Module and then to Object.

> Class.superclass
 => Module 
> Module.superclass
 => Object

And now, through the power of my very limited Open Office Drawing skills, i shall try to demonstrate what i think the diagram really looks like.

So where did Module come from? Why is a Class also a Module? And if Numeric is of class Class, why is its superclass not also Module?

I don’t think it’s particularly important to know these things, but they were interesting questions and i don’t know the answers.

Does anyone know?

Installing Io

I am currently installing Io to get ready for week 2 of Seven Languages in Seven Weeks.

I’m on Mac OS X Snow Leopard and i have the very excellent homebrew by Max Howell and there is a recipe for Io. So it should be as simple as:

brew install io

It has downloaded and is currently installing cmake, which is a dependency. That’s taking a while.

Aha, now it is doing libgsml … that was quick.

Now it’s cloning io from github.com/stevedekorte/io and using cmake to install it.

Done! The whole process took 17 minutes.

But, oh dear!

$ io
dyld: Library not loaded: libbasekit.dylib
  Referenced from: /Users/aimee/Developer/bin/io
  Reason: image not found
zsh: trace trap  io

I’m going to post this up and see if someone knows the answer. I’ll update here once i have it working.

Update

Thanks to Evadne for pointing me to Installing Io on my Mac where i got the clue to make this work.

Since i installed Io with homebrew, it has gone into /Users/aimee/Developer for me. I need to tell it to find the dyld libbasekit library in the same place.

I use zsh so this just needs to go in my .zshrc file:

export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:~/Developer/lib

Now we’re all set!

$ io
Io 20090105
Io> "Hi ho, Io" print
Hi ho, Io==> Hi ho, Io

Now i’m ready for monday! :)

Update 2

I since found out that changing my dynamic library broke gitx for me. So i’m doing it this way instead:

alias io='DYLD_LIBRARY_PATH=~/Developer/lib ~/Developer/bin/io'

Now everything works :)

Week1 Day 3 – Ruby metaprogramming

Seven Languages in Seven Weeks really does more than scratch the surface of a language. It shows off what each language does best. Ruby is great at expressive metaprogramming, so we wasted no time into diving deep into not one, but three types of metaprogramming:

  1. Opening an existing class to add extra methods
  2. Using method_missing to define dynamic methods
  3. Creating mixin modules to extend functionality

For me, this was highly insightful. Metaprogramming is always something that Other People do. I have written a couple of gems before, but i didn’t really understand what i was doing – i just played around copying examples until it did what i wanted. Or more often, i would be quick to use inheritance, not realising that a mixin module might serve me better.

I was inspired by Seven Languages in Seven Weeks where it showed how to start with a simple module and then adapt it a little to make it even more flexible. In future i will refer to this book to guide me as it explains so well what’s going on.

module ActsAsCsv

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def acts_as_csv
      include InstanceMethods
    end
  end

  module InstanceMethods
    attr_accessor :headers, :csv_contents

    def initialize
      read
    end

    def read
      # ...
    end
  end

end

class RubyCsv
  include ActsAsCsv
  acts_as_csv
end

We write a module which, once included, the first thing it does is adds another module to the class which included it. That module provides a macro method which, when called, adds instance methods and attributes.

I now realise that there is nothing special about the module names ClassMethods and InstanceMethods. They are just named that way for clarity. There is not really any voodoo going on here.

When trying to add an each method i started off like this:

m = RubyCsv.new
m.each{|row| puts row.inspect }

I implemented an each method like this:

def each(&block)
  @csv_contents.each {|r| block.call(r) }
end

Sure enough, i was able to inspect the row. But then we wanted to do this, where one of the headings in the CSV file was ‘one’:

m.each{|row| puts row.one }

“No problem!” i thought. “Time for a method_missing” … but then i realised something i definitely would not have anticipated without doing the exercise.

undefined method `one' for ["lions", "tigers"]:Array (NoMethodError)

There you see the problem?! I’m working with an array at this point! Looking back at the book, it gave me a hint, which i had missed:

Modify the CSV application to support an each method to return a CsvRow object.

Ah, so that’s the answer! I modified my each method to do this:

def each(&block)
  @csv_contents.each do |r|
    row = CsvRow.new(@headings, r)
    block.call(row)
  end
end

I had to decide where to put the CsvRow class, and decided to put it as part of the module so there’s nothing else i had to require when mixing in the module.

I needed to pass the headings found, so that the row could implement its method_missing and find the right position in the array. The CsvRow class ended up like this:

class CsvRow
  attr :contents, :headers

   def initialize(headers, contents)
    @headers = headers
    @contents = contents
  end

  def method_missing(method)
    index = @headers.index(method.to_s)
    raise "No heading '#{method}' in the CSV file." if index.nil?
    @contents[index]
  end

end

The full solution can be found here: week1-ruby/acts_as_csv_module.rb

I am really glad of the opportunity to explore and understand Ruby metaprogramming a lot better. I am also extremely excited for what i’m going to learn in the other six languages in the next six weeks. This has set me up to expect some really awesome things!

Week 1 Day 2 – Diving deeper into Ruby

I had a really great day. Gave myself a day off from working, and went to London to meet my apprentice Rohit, see a few friends and go to eXtreme Tuesday Club in the evening.

At 6pm i met with Dan in Covent Garden and we worked through a bit of #7languages7weeks Day 2 together. We came up with three ways of splitting up an array into groups of four, ending with the beautifully elegant each_slice method. You can see the result of our efforts here: week1-ruby/day2.rb

I worked through the remaining exercises on the train home. One thing really caught me out, which is how Ruby is so eager to convert hashes to arrays when you iterate. For example:

> hash = {1 => 'one', 2 => 'two', 3 => 'three'}
=> {1=>"one", 2=>"two", 3=>"three"}
> hash.each {|part| puts part.inspect }
[1, "one"]
[2, "two"]
[3, "three"]

See that?! Surprise Array!

I had originally said that you can’t convert an array to a hash, but in a case like this you can, and to solve the tree initialization exercise i found i had to. Something like this:

> hash = {1 => 'one', 2 => 'two', 3 => 'three'}
=> {1=>"one", 2=>"two", 3=>"three"}
> hash.each {|part| puts ({part.first => part.last}).inspect }
{1=>"one"}
{2=>"two"}
{3=>"three"}

My solution to the family tree exercise can be found here: week1-ruby/tree.rb

Finally, the find-in-file exercise. I really like this one. The book said the solution was simple, and my word, it truly is.

File.open('tree.rb').each_with_index do |line, line_number|
  puts "#{line_number}: #{line}" if line =~ /tree/
end

That’s it! So neat. I have always liked the application of the each method on a File. Here’s the output of the program:

$ ruby read_file.rb 
13:   def initialize_with_hash(tree)
14:     tree.each_pair do |name, children|
35: ruby_tree = Tree.new('Ruby', [Tree.new('Reia'), Tree.new('MacRuby')])
38: ruby_tree.visit {|node| puts node.node_name }
41: puts 'Visiting entire tree'
42: ruby_tree.visit_all{|node| puts node.node_name }
44: family_tree = Tree.new({'grandpa' => {
50: puts 'Visiting family tree'
51: family_tree.visit_all{|node| puts node.node_name }

Very neat! Although i’ve been programming in Ruby for a long time, i am appreciating its beauty and simplicity all the more tonight!

Update

Since looking at Alberto’s excellent solutions and checking the Ruby Hash#each documentation, i now realise that the each method is supposed to take two elements in the block. For some reason i always thought you had to use each_pair for that. So there we go, talk about failing publicly! :)