Monday, 19 September 2011

The Road to Oxiana

by Robert Byron

Byron  was a pre WWII travel writer, indeed he died when his ship was torpedoed in 1941. The Road to Oxiana is the diary of a trip he made to Afghanistan in 1933-4, it can be read on many levels, from 'travelogue of an upper-class brit abroad' to the 'wanderings of an archaeological aesthete'.

One of the main joys of the book is that Byron is always well-written and forthright, for instance on the Venice Lido from the first paragraph :-
 The bathing, on a calm day, must be the worst in Europe: water like hot saliva, cigar-ends floating into one's mouth and shoals of jellyfish.

Lifar came to dinner. Bertie mentioned that all whales have syphilis.
The journey is travelling in the old style, things happen when they will, cars break, rivers flood roads, visas are granted and denied on a whim -his whole trip seems to run several months over its allotted time, and in the end he never does see the Oxus.

Byron's true passion if for architecture -I advise you to cultivate a knowledge of the squinch, it'll be useful for scrabble if nothing else- again the best I can do is to quote, this is about the Friday Mosque in Isfahan :

...But while the larger lacked the experience necessary to its scale the smaller embodies that precious moment between too little and too much,when the elements of construction have been refined of superfluous bulk, yet still withstand the allurements of superfluous grace; so that each element, like the muscles of a trained athlete, performs its function with winged precision, not concealing its effort as over refinement will do, but adjusting it to the highest degree on intellectual meaning.
 All in all it's worth taking the journey with Byron and listening to his story telling on the way. You wouldn't want to be on the sharp end of his tongue though -even if he does dish it out fairly impartially.

Wednesday, 7 September 2011

Haskell - 7 languages in 7 weeks, Day 2

Haskell Day 2 Exercises

Write a Haskell function to convert a string to a number. The string should be in the form of $2,345,678.99 and can possibly have leading zeros.

As I mentioned in the last post, there was a better way to solve this than tail recursion.


strToNum :: String -> Float
strToNum(str) = let num = [x|x <- str,  (x >= '0' && x <= '9') || x == '.']
       in read num :: Float

This function uses list comprehension to filter the string for valid characters and the uses read to convert the filtered string into a floating point number. As you can see it's very concise, and when you are used to the form very readable. This says num is all the valid (0-9 and .) characters from the string str. 

Write a function that takes an argument x and returns a lazy sequence that has every third number, starting with x. Then, write a function that includes every fifth number, beginning with y. Combine these functions through composition to return every eighth number, beginning with x + y.

stepList x n = take 5 [x,x+n..]

threeList x = stepList x 3
fiveList x = stepList x 5

eightList x y = zipWith (+) (threeList x) (fiveList y)


So, the lazy sequence is [x,x+n..] to stop things running off into infinity I've used take to perform the lazy eveluation. Again, Haskell can be very concise -look at zipWith in eightList.


Use a partially applied function to define a function that will return half of a number and another that will append \n to the end of any string.


half = (*) 0.5



This is quite cunning (of Haskell). Inside Hskell all functions are, I believe, curried -that is they take only one argument. As a bit of syntactic sugar Haskell support infix operators, but you can force them to their curried form but surrounding the operator in brackets.  Since the functions are curried they are quite happy to have a dangling second argument, in fact we have here a function that is 'multiply by 0.5'.


backAppend x y = y ++ x
append = backAppend "\n"



The same applies to the append function here, only we have had to define backAppend to get the arguments the way round we want.

I'm going to leave the second set for now, and maybe come back to them at the end.

Tuesday, 6 September 2011

Haskell, where vs let in guards

I'm making a stab at learning Haskell, a functional programming language, and as part of it I'm going through the section in Seven Languages in Seven Weeks, one of the exercises is to convert a string representation of a number to a real (floating point) number, so " $2,345,678.99" to  2345678.99.
Here's my first stab :

import Char

strToNum :: String -> Float

sToN :: (Float, Int, String) -> Float
sToN (acc, dec_place, []) = acc
sToN (acc, dec_place, xs)
        | head xs == '$' = sToN (acc, dec_place, tail xs)
        | head xs == ',' = sToN (acc, dec_place, tail xs)
        | head xs == '.' = sToN (acc, 1, tail xs)
        | dec_place > 0 =
                let  newacc = acc + (fromIntegral (digitToInt (head xs)) )  / (10.0  ^ dec_place)
                in sToN (newacc, dec_place + 1, tail xs)
        | otherwise =
                let newacc = acc * 10.0 + (fromIntegral (digitToInt (head xs)) )
                in sToN (newacc, dec_place, tail xs)

strToNum "" = 0.0
strToNum(xs) = sToN (0.0, 0, xs)

It's a bit brute force and ignorance, but it works. Just thought of a more elegant solution though. The point of this post is the use of 'let' rather than 'where' in the guard expression. The guards (| expressions) handle the various characters and states of the string, and in the two that alter the accumulator define the new value via a 'let'. Initially I tried using a 'where' for this, but it seems that you can only have one per pattern sequence, it would seem that this is because 'let' is a proper expression whilst 'where' is not.

BTW I also tried this with lambdas, but fell foul of the type system.

I quite like this pattern matching approach in general, and have used it in Perl a lot, as it is quite easy to see each 'case' and the logic that goes with it.

Sunday, 14 August 2011

Want to Learn About Computers?

From scratch, then get hold of Charles Petzold's book Code .


Unfortunately Code wasn't written when I was doing wire wraps on breadboards try to build a half adder using bc109s (or what ever transitors we were using) -if it had been the cybernetics weekend I spent as a teenager might have made a whole lot more sense.

Petzold starts right at the beginning with light bulbs and switches, spends a long time with relays and ends up with those classic microprocessors the 8080 and the 6800. If you stick with him, not a hard task, then you will understand how a modern computer works. I haven't quite finished it, but the book is restricted to classic von Neuman machines, I haven't seen any discussion of massively parallel architectures, RISC processors or data-flow engines, never mind quantum computers, but you can go on from here knowing all the basics and with the understanding to tackle more exotic designs.

The book isn't all hardware, it also covers numbering systems, text encoding, machine code and assembler -at the lower end with a brief look at operating systems and languages at the higher end of abstraction.

Monday, 28 March 2011

City Life

An example of London life that happened to me in the week.

I'm heading back to Liverpool Street to catch the train home -just another worker ant focused on the clock, when :

'Can I ask you a question'

Oh god I think, I take a look at the questioner, no clipboard that's a good sign, scabs on the face and swaying a bit -not so good. Still  I've got 5 minutes to spare, it might be quicker to play along with him.

'Go on then -if you're quick'

'Do you remember Dudley wossname -was in that film with that bird'



Ok, that came from nowhere, however I'm of the vintage that Bo Derek made a big impression on (well the male half anyway -and if the number of cornrow hairdos that were about on blondes at the time was any guide- the females weren't entirely immune).

'Uh, yes Dudley Moore'

'Who was it who was his partner, you know in the act, do you know?'

'Peter Cook' I reply.

'Brilliant mate -I had this bet with my mate that he was wrong and you've won me 20 quid'

'Who did he think it was then?'

'Peter O'Toole, wanker. I told him he was Dracula.'

Made me smile. And it's an excuse to put up a picture of Bo.



Wednesday, 9 March 2011

Turing got there first -again.

Alan Turing

I was doing some research into test driven development and came across Tony Hoare's paper  The Emperors Old Clothes . Hoare is a big name in the history of computer science, inventing Quicksort at an early age and then C.S.P -I have had the misfortune to program in Occam (and Ada) which implement this, nothing wrong with the concept or really the language -but Occam simulated on a vintage PC wasn't good.

Hoare's paper is well worth a read, both from a historical perspective and for the all too familiar view of projects going horribly wrong -in this case Algol 68, PL/1 and Ada. Helped by mandated use from the military Ada did finally take off -but so did the Bristol Brabazon - but the language failed to achieve the popularity hoped for and we all ended up using C++ for our sins (which must have been many).

Anyway, back to Turing, it seems he wrote a paper in 1949 (yup) entitled 'Checking a Large Routine' the opening paragraph reads :- 
"How can one check a large routine in the sense of making sure that it’s right? In order that the man who checks may not have too difficult a task, the programmer should make a number of definite assertions which can be checked individually, and from which the correctness of the whole program easily follows"
 Sounds like the basics of Test Driven Development to me.


Sunday, 6 March 2011

Why I hate setters and getters (especially in PHP).

Whatever you think about object oriented programming (and the phrase ‘Emperors New Clothes’ has been known to pass my lips, although I’m not so dogmatic now.) there’s a point where the syntactic sugar turns to syntactic saccharine -and that point is accessor methods.

Whilst I acknowledge the usefulness of encapsulation and limited visibility I loathe having to write reams of setThis() and getThat() for every blasted variable I want to use. I was going through the Zend Framework tutorial and there’s a simple four field model in there, which generates eight methods, life is too short. The model already exploits __set and __get which allow controlled access to hidden properties, so why not go the whole hog? Here’s a version that calls an accessor method if there is one (you might need to do some extra processing or formatting in it) but otherwise returns the protected variable.


class SomeClass {
    protected $_comment;
    protected $_created;
    protected $_email;
    protected $_id;

    public function __get($name)
    {
       $method = 'get' . $name;
       if (('mapper' == $name)) {
           throw new Exception('Invalid guestbook property');
       }
       if(method_exists($this, $method)) {
           return $this->$method();
       }

       $attr = "_$name";
       if(property_exists($this,$attr)) {
           return $this->$attr;
       }
       throw new Exception('Invalid guestbook property');
    }  
}

Instead of defining a setId method and calling a $someObj->setId(3), you don’t define the method and use $someObj->id = 3.

Personally I’d probably turn this into an abstract base class to support the model classes, leaving the individual classes to supply specific accessor methods if needed -thus getting rid of reams of code that I’d need to maintain. There are times when you wouldn’t use this approach, but for the database mapping example given it’s a bit of a no brainer.

Why especially in PHP? Because it’s not an O.O. language, it’s a scripting language, I like the ability to use O.O. syntax when I think it adds clarity to the program and I like the fact that I don’t have to if I think it makes life harder. Additionally libraries like Zend Framework should make life quicker and easier, it is the point of them after all, and not slower, harder and more verbose.

BTW don’t let this put you off Zend Framework, it’s a good piece of work and I’ve built a few systems using it.

linkedin