Sunday, August 23, 2015

Game Of Life and Pharo

For me, watching executions of the Conway's Game of Life is hypnotizing. It is interesting how a small set of simple rules creates such complex and beautiful patterns.

Creating a naive version of the Game of Life is a small programming task, which is ideal for learning a new programming language. I used it to create a small example in Pharo which is a Smalltalk based language. For its implementation I also used the Morphic UI environment.

Game of life Morph executing

The program is written as a Morph, which is the name of an object on the screen. Here's the definition:

Morph subclass: #GameOfLifeMorph
        instanceVariableNames: 'columns rows content mouseInteraction nextGrid'
        classVariableNames: ''
        category: 'GameOfLife'

Drawing the matrix with the contents of the game is very simple:

drawing
drawOn: canvas
     "Draws the game of life widget with the current state"
     | cellWidth cellHeight rectangle  cellColor cellValue|
      
     cellWidth :=   (self width) / columns.
     cellHeight :=   (self height) / rows.
     1 to: rows do: [ :row |
          1 to: columns do: [ :column |
                 cellValue := (content at: row at: column).
                 cellColor := cellValue = 1 ifTrue: [ Color black ] ifFalse: [ Color white  ].
                 rectangle := Rectangle left: (self bounds left) + ((column - 1)*cellWidth) 
                                        right: (self bounds left) + ((column - 1)*cellWidth) + cellWidth
                                        top: (self bounds top) + ((row - 1)*cellHeight )
                                         bottom: (self bounds top) + ((row - 1)*cellHeight ) + cellHeight.
         
                 cellValue = 1 ifTrue: [canvas fillRectangle:  rectangle color:  cellColor]
                               ifFalse: [canvas frameAndFillRectangle: rectangle 
                                                   fillColor:  (Color white) 
                                                   borderWidth: 1 
                                                   borderColor: (Color black)].
             ]
       ].
       ^self.

The implementation of the animation part of the program was created using the step and stepTime methods.

stepping and presenter
step
      "Verifies the rules of the Game Of Life"
      | tmp |
      
      1 to: rows do:  [ :row | 
          1 to: columns do:  [ :column |
              nextGrid at: row at: column put: (self getNextGenerationFor: row column: column).
          ]
      ].
      tmp := content.
      content := nextGrid.
      nextGrid := tmp.
      self changed.

The following method shows how to get the next generation for a given (row, column) individual.

This method is going to check for the game of life rules.

game of life rules
getNextGenerationFor: row column: column
      "Verifies the Game Of Life rules"
      |topLeft top topRight left right bottomLeft bottomRight bottom neighbors|

      topLeft :=  self getCellValue: (row - 1) column: (column - 1).
      top := self getCellValue: (row - 1) column: column.
      left := self getCellValue: row column: (column - 1).
      right := self getCellValue: row column: (column + 1).
      topRight := self getCellValue: (row - 1) column: (column + 1).
      bottomRight := self getCellValue: (row + 1) column: (column + 1).
      bottom := self getCellValue: (row + 1) column: column.
      bottomLeft := self getCellValue: (row + 1) column: (column - 1).
   
      neighbors := topLeft + top + left + right + topRight + bottomRight + bottom  + bottomLeft.

      ^ ((content at: row at: column) = 1) 
             ifTrue: [ (neighbors < 2 | (neighbors > 3)) ifTrue: [ 0 ] ifFalse: [ 1 ]  ] 
             ifFalse: [ (neighbors = 3) ifTrue: [ 1 ] ifFalse: [ 0 ] ].

The last statement verifies the rules:

  • A live cell with less than two neighbors dies in the next generation
  • A live cell with two or three neighbors survives to the next generation
  • A live cell with more than three neighbors dies
  • A dead cell with three neighbors becomes alive in the next generation

To open this Morph into the Pharo environment we can evaluate:

|m|
m := GameOfLifeMorph rows: 30 columns: 30.
m width: 300 ;height: 300 ; openInWorld.
m stopStepping.
m enableMouseInteraction . 

To start the execution we can evaluate:


GameOfLifeMorph allInstances last startStepping.

Programming in Pharo is a very interesting experience. This mainly because the development environment is really integrated with the program you are developing. Something that called my attention is how you can define missing code while debugging and without stopping the debugging session.

The code for this experiment can be found here: http://github.com/ldfallas/GameOfLife

Monday, August 10, 2015

Starting with Pharo and external source control

Here's a series of steps I'm following for using Git to store the source code of some Pharo experiments I'm working on.

I'm starting learning about Pharo. The information on this post is based on the nice Pharo and Github using Sourcetree video and an introduction to Monticello.

Configuring a repository

We can start by creating a repository that is located in the filesystem. To define configure this repository we open the "Monticello Browser" from the "World" menu and press the "+Repository" button.

We are going to select the filetree:// repository type. This is useful to store the code in separate files.

When this option is selected the UI will prompt us for the folder where the code will be stored. We are going to specify a directory where we executed the git init command . Other source control systems could be used to manage this directory since it will contain the source code as text files.

Creating a package

Now we're going to define a package where we will the create the code to be stored in source control. To define the package we open the "Monticello Browser" from the "World" menu and press the "+Package" button.

Now we can create a class inside this package. We are going to define the GameOfLifeMorph class to be in the GameOfLife category.

We are going to add a method to the GameOfLifeMorph class.

After adding these elements we can save the changes to the GameOfLife package. We can review the changes before saving by pressing the Changes button on the "Monticello" browser.

This option opens the following screen to review the changes before saving.

After reviewing the changes we can save the changes to the file system using the Save button in the "Monticello Browser" window. Now we can go to the command line to directory we selected when creating the repository and execute a git status command.

~/devel/pharo/GameOfLife$ git add .filetree GameOfLife.package/
~/devel/pharo/GameOfLife$ git status
On branch master

Initial commit

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

        new file:   .filetree
        new file:   GameOfLife.package/.filetree
        new file:   GameOfLife.package/GameOfLifeMorph.class/README.md
        new file:   GameOfLife.package/GameOfLifeMorph.class/instance/initWithRows.columns..st
        new file:   GameOfLife.package/GameOfLifeMorph.class/methodProperties.json
        new file:   GameOfLife.package/GameOfLifeMorph.class/properties.json
        new file:   GameOfLife.package/monticello.meta/categories.st
        new file:   GameOfLife.package/monticello.meta/initializers.st
        new file:   GameOfLife.package/monticello.meta/package
        new file:   GameOfLife.package/monticello.meta/version
        new file:   GameOfLife.package/properties.json

~/devel/pharo/GameOfLife$ git commit -m "First commit"

Sunday, June 29, 2014

Writing (very) simple tests in C

A couple of weeks ago I was trying to write some small tests for a toy C program I'm working on

Although there are some nice frameworks for writing units tests in C, I wanted something minimal. So I wrote some functions that let me do that:


void run_test(char* testname, void (*testfunc)()) {
  printf("Running %s\n", testname);
  testfunc();
}

#define RUN_TEST(testname) run_test(#testname, testname);

void tassert(int result, const char* testName, char* formatString, ...) {

  va_list args;
  va_start(args, formatString);
  if (!result) {
    printf("ASSERT FAILED in test \"%s\": ", testName);
    vprintf(formatString, args);
    printf("\n");
  }
  va_end(args);
}

void tassert_equal_ints(int expectedValue,int actualValue, const char* testName) {
  int comparisonResult;
  comparisonResult = expectedValue == actualValue;
  tassert(comparisonResult,
          testName,
          "expected: %d, actual %d", 
          expectedValue, 
          actualValue);
}

These very simple functions allowed me to write small tests. For example:

void testTreeFormation1() {
   Expr* expr;
   OutStream stringOut;
   
   stringOut = createStringOutStream(15);
   expr =
      createAddition(
            createAddition(
               createNumLiteral(10.2),
               createNumLiteral(-13)),
            createNumLiteral(13));

   printExpr(expr, &stringOut);

   tassert_equal_strings("<<11.2 + -13> + 13>",
                        getStringFromStringOutStream(&stringOut),
                        __FUNCTION__);
   
   deepReleaseExpr(expr);
   destroyOutStream(&stringOut);
}

This test is verifies that an expression tree is created as expected.

The main method to execute the tests looks like this:

int main(int argc, char* argv[]) {
  
  printf("Running tests\n");
  
  RUN_TEST(testStrBuffer1);
  RUN_TEST(testStrBuffer2);
  RUN_TEST(testStrBuffer3);
  RUN_TEST(testStrBuffer4);
  RUN_TEST(test1);
  RUN_TEST(testTreeFormation1);
  ...
}

Saturday, October 6, 2012

An example use of Haskell Views

In this post I'm going to show how I'm using Haskell Views in a small Scheme implementation to deal with syntactic sugar.

One example of syntactic sugar in Scheme is the way to define functions. You can do it the following way:


(define square (lambda (x) (* x x))
But you can also use the following shortcut:

(define (square x) (* x x))

I'm going to take advantage of Haskell Views to simplify the implementation of this feature. The following code shows the data type representing Scheme code.


       data Expr a where
               ScSymbol :: String -> Expr a
               ScString :: String -> Expr a
               ScNumber :: Integer -> Expr a
               ScDouble :: Double -> Expr a 
               ScCons :: (Expr a) -> (Expr a) -> (Expr a)
               ScNil :: Expr a
               ScBool :: Bool -> Expr a
               ScQuote :: (Expr a) -> Expr a
               ScEnv ::  (Expr a)
               ScChar :: Char -> Expr a
               ScPort :: Handle -> Expr a
               ScClosure :: ScExecutable a =>  [String] -> a -> (Env a) -> Expr a
               ScPrimitive ::  ([Expr a] -> ScInterpreterMonad (Expr a))  -> Expr a

As a side note,I'm using ScCons/ScNil to represent lists which is different from the way "Write Yourself a Scheme in 48 Hours" defines them (a wrapper around a Haskell list). This decision turned out to be incorrect since manipulating a Haskell list is easier.

Given Scheme datatype definition we can represent the following function definition:

(define (id x) x)

As the following structure:


  (ScCons
     (ScSymbol "define")
     (ScCons
        (ScCons
           (ScSymbol "id")   
           (ScCons
              (ScSymbol "x")
              ScNil))
        (ScCons
           (ScSymbol "x")
           ScNil)))

And the following code:

(define id (lambda (x) x))

Using the following structure


  (ScCons
     (ScSymbol "define")
     (ScCons
        (ScSymbol "id")
        (ScCons
           (ScCons
              (ScSymbol "lambda")
              (ScCons
                 (ScCons
                    (ScSymbol "x")
                    ScNil)
                 (ScCons
                    (ScSymbol "x")
                    ScNil)))
           ScNil)))

Using Haskell Views we can create a view that returns the desired parts:


defineView :: (Expr a) -> Maybe (String, Expr a)
defineView  (ScCons 
             (ScSymbol "define")
             (ScCons 
                 name@(ScSymbol symbolToDefine)
                 (ScCons
                    value
                    ScNil))) = Just (symbolToDefine, value)
defineView  (ScCons 
                (ScSymbol "define")
                (ScCons 
                   (ScCons 
                      name@(ScSymbol symbolToDefine)
                      args)
                   (ScCons
                       value
                       ScNil))) = Just (symbolToDefine, 
                                        (ScCons (ScSymbol "lambda") 
                                                (ScCons args 
                                                        (ScCons value ScNil))))
defineView _ = Nothing

As shown above, this view will extract the parts of the original expression or create the necessary elements in the case of the function definition. Also it will fail in case of non supported syntax.

This view is used in the following code:


prepare (defineView -> Just (symbolToDefine, value)) = 
         do
            preparedValue <- prepare value
            return $ ScSeqDefine symbolToDefine preparedValue 

Code for this post is available in the ToyScheme repo.

Saturday, September 22, 2012

A quick look at Haskell Views

Haskell views is a language extension that allows calling functions as part of the pattern matching process. A simple example looks like this:

 
square x = x*x

doSomething :: Integer -> Integer -> Integer
doSomething (square -> squared) other = squared + other

The real power of this feature is that you can combine it with other pattern matching elements. For example, in the following code the 'rgroups' function is used to match a regular expression and return a list with the groups resulting of this matching process. This function is used as part of the 'classify' function.

rgroups :: String -> String -> [String]
rgroups regex text = result
  where
     matchResult :: (String, String, String, [String])
     matchResult = text =~ regex
     (_, _, _, result) = matchResult
   

data Record =
  Person String Integer
  | Company String
  | Unknown String
 deriving Show

classify  ((rgroups "([a-z]*):[ ]*([a-z]*)[ ]*([0-9]+)") -> ["person", personName, age]) =
  Person personName (read age)
classify  ((rgroups "([a-z]*):[ ]*([a-z]*)") -> ["company", personName]) =
  Company personName
classify line =
  Unknown line

We can use this function as follows:


txtlines = ["company:  testcomp",
            "person: someone    30",
            "oasd",
            "person:another    40"]

*Main>  map classify txtlines
[Company "testcomp",Person "someone" 30,Unknown "oasd",Person "another" 40]

Since this is a language extension we need to activate it by using a GHC command line argument or by adding the following code at the top of the file.


{-# LANGUAGE ViewPatterns #-}

More information can be found in the ViewPatterns section of the GHC wiki. This feature is an inspiration for the Scala extractors and F# active patterns which I talked about in previous posts.

Friday, February 10, 2012

Printing Scheme-like expressions using pretty printing combinators

In this post I'm going to show a small printer for Scheme-like expressions using pretty printing combinators in Haskell.

The data type definition for these expressions looks like this:

data Expr = ScSymbol String
            | ScString String
            | ScNumber Integer
            | ScDouble Double 
            | ScCons Expr Expr
            | ScNil
            | ScBool Bool
            | ScQuote Expr
     deriving Show

The pretty printing combinator library is located in the Text.PrettyPrint.HughesPJ package.

import Text.PrettyPrint.HughesPJ 

toStringP :: Expr -> Doc

The Doc data type represents a document to be printed. The definition for printing the atomic expressions looks pretty straightforward:

toStringP (ScSymbol name) = text name
toStringP (ScNumber num) = integer num
toStringP (ScDouble num) = double num
toStringP ScNil = text "()"
toStringP (ScQuote exp) = text "'" <> (toStringP exp)
toStringP (ScBool value) = text $ if value then "#t" else "#f"
toStringP (ScString str) = doubleQuotes $ text str

This code uses the text, integer and double functions to generate documents for each atomic part.

Now, the interesting part is defining the way to print ScCons which represent linked lists. The definition looks like this:

toStringP (ScCons first rest) = parens ( hang (toStringP first) 3  (sep $ toStringPCons rest))
  where
     toStringPCons (ScCons part rest) =  ((toStringP part) : (toStringPCons rest))
     toStringPCons ScNil = []
     toStringPCons other = [(text ".") , (toStringP other) ]

Here we use just three combinator functions:

  1. parens: which creates a document that will be rendered inside parentheses
  2. sep: which combines document parts depending on the context
  3. hang: which will allow us to add a nice effect to composed expressions by nesting the contents when necessary. In this case we specify indentation by 3 characters.

The following function is used to parse the expressions using a parser from a previous post and then print the result with a given style.

    parseAndRender style text =
       case (parseIt text) of
         Right parsed -> putStr $ renderStyle style  $ toStringP parsed
         _ -> putStr "ParseError"

Now we can print an example:

    smallTest style =
      parseAndRender style "(html (head (title \"Hello world\")) (body (p \"Hi\") (ol (li \"First\") (li \"Second\"))))"

We can print using the default style like using the style definition:

*SCPPrint> smallTest style
(html
    (head (title "Hello world"))
    (body (p "Hi") (ol (li "First") (li "Second"))))

The default style definition specifies a line width of 100 characters. We can modify it to be shorter, for example:

*SCPPrint> smallTest style { lineLength =  40 }
(html
    (head
        (title "Hello world"))
    (body
        (p "Hi")
        (ol
            (li "First")
            (li "Second"))))

It is impressive what can be accomplished with such a small number of definitions. For more information about this pretty printing combinator library and its design process see: The Design of a Pretty-printing Library by John Hughes

Tuesday, January 31, 2012

A quick look at Haskell records

While reading the Parsec documentation I learned about a nice technique used to create language definitions. For example:
idSymbol = oneOf ":!$%&*+/<=>?@\\^|-~"

schemeLanguageDef :: LanguageDef st
schemeLanguageDef = emptyDef { 
                   commentLine = ";;"
                   , identStart = letter <|> idSymbol
                   , identLetter = alphaNum <|> idSymbol
                   , opStart = parserZero
                   , opLetter = parserZero
                 }

In this case we are creating a small language definition based on emptyDef. We're saying that we want all what emptyDef has but changing the values of commentLine, identStart, identLetter, opStart and opLetter.

The Text.Parsec.Language package contains several predefined language definitions which you can use to create yours. Some of these definitions are based on each other, for example the haskell98Def and haskellStyle. This is accomplished using Haskell record syntax for defining data types.

Records in Haskell allow the creation of abstract data type definitions that contain named fields . For example, here's a small definition of a data type to store the information of an editor color theme:
data Theme = ColorTheme {
                     keywordsColor :: Color,
                     backgroundColor :: Color,
                     fontSize :: Int,
                     operatorsColor :: Color,
                     literalsColor :: Color
                }
        deriving Show
An instance of this record can be created as follows:
   baseTheme = ColorTheme { keywordsColor = Black,
                            backgroundColor = White,
                            fontSize = 10,
                            operatorsColor = Black,
                            literalsColor = Black }

One nice feature of Haskell records is that it allows the creation of a new record instance based on a existing one. Back to our artificial example, say that we want to create a dark theme which is the same as the base but with colors inverted.
   darkTheme = baseTheme {
                           keywordsColor = White,
                           backgroundColor = Black,
                           operatorsColor = White,
                           literalsColor = White
                         } 
Here we're saying that we want a copy of baseTheme with keywordsColor, backgroundColor, operatorsColor and literalsColor changed to another value.

Pattern matching can be used to extract parts of the record. For example, say that we want to define a function to increase the current font size of a theme:
  increaseFontSize :: Int -> Theme -> Theme
  increaseFontSize amount theme@ColorTheme { fontSize = currentFontSize} =
        theme { fontSize = currentFontSize + amount } 

We can use this definition :

*Tests> increaseFontSize 5 baseTheme
ColorTheme {keywordsColor = Black, backgroundColor = White, fontSize = 15, operatorsColor = Black, literalsColor = Black}
Also accesor functions are defined for each part of the record. For example:
*Tests> backgroundColor baseTheme
White

For future posts I'm going to explore similar features that exist in other programming languages.