Sunday, April 10, 2016

Determinism categories in Mercury

When you define a predicate in Mercury, you have to specify if it can fail or succeed more than once. This is called a determinism category.

The category is specified as part of a predicate (or function) declaration. For example:

:- pred get_partitions(
          list(int)::in,
              list(list(int))::out) is multi.

The is multi section says that this predicate belongs to the multi category.

The following tables describe the main determinism categories.

Maximum number of solutions:

Mode 1 > 1
det x
multi x
semidet x
nondet x

Failure:

Mode Can fail?
det no
multi no
semidet yes
nondet yes

(Based on information from https://mercurylang.org/information/doc-latest/mercury_ref/Determinism-categories.html#Determinism-categories ).

Other categories exist : erroneous , failure, cc_mult and cc_nondet. These are not discussed in this post, see the link above for more info.

Now a some of each category:

det

These predicates in must always succeed . For example:

:- pred list_length(list(int)::in, int::out) is det.

list_length([_|R], Length) :-
   list_length(R,SubListLength),
   Length = SubListLength + 1.
list_length([], 0).

In this case this predicate is going to calculate the size of a list. It should not fail.

semidet

These predicates can either succeed or fail. For example the following code shows the definition of a first_even_number predicate.

:- pred first_even_number(list(int)::in, int::out) 
           is semidet.

first_even_number([X|R], N) :-
   (if (X mod  2) = 0 then
       N = X
    else
       first_even_number(R,N)).

Notice that this predicate can fail for a couple of reasons:

  • The input list may be empty
  • The input list may not contain an even number

I think it's pretty nice that you these situations will be handled without explicitly writing code for it.

A use of this predicate looks like this:

...
   (if first_even_number([3,41,5,32,342], EvenNumber) then
       io.write_string("First even number: ", !IO),
       io.write(EvenNumber, !IO)
    else
       io.write("Not even number found", !IO)
    ).

Another think that's pretty nice about Mercury is that, the compiler is going to detect inconsistent determinism annotations. For example, if I change the declaration of the predicate to:

:- pred first_even_number(list(int)::in, int::out) 
           is det.

The compiler is going to fail with the following error:

testsolutions.m:093: In `first_even_number'(in, out):
testsolutions.m:093:   error: determinism declaration not satisfied.
testsolutions.m:093:   Declared `det', inferred `semidet'.

multi

The multi category is used for predicates that succeed in multiple ways. At least one solution exists.

For example the following predicate is used to get a pair of lists that, when concatenated together, result in the input list (ex. [1,2,3] result in { [1],[2,3] }) .

:- pred partitions(list(int)::in, 
           {list(int), list(int)}::out) is multi.


partitions(InputList,Output) :-
(
   Output = {[] ,  InputList}
 ;
   InputList = [A|TMP],
   partitions(TMP,{R,B}),
   Output = { [A|R], B }
).

This predicate is multi because we can get several different pairs of lists that from an input list. For example:

main(!IO) :-
   solutions(partitions([513,242,355,4]),Pairs1),
   io.write(Pairs1,!IO),
   io.nl(!IO).

Running this program result in the following output:

[{[], [513, 242, 355, 4]}, {[513], [242, 355, 4]}, {[513, 242], [355, 4]}, {[513, 242, 355], [4]}, {[513, 242, 355, 4], []}]

In the case we use the solutions/2 Mercury predicate to get a list from the generated solutions.

It's important to note that multi predicates must not fail.

nondet

Finally the nondet category is used for predicates that result on 0 or many solutions.

For example the following predicate result on an even number that is part of the input list.

:- pred even_member(list(int)::in, int::out) is nondet.

even_member([X|_], X) :-
   (X mod  2) = 0.
even_member([_|Rest], X) :-
  even_member(Rest,X).

This predicate is nondet because :

  • The list may be empty
  • It may not contain an even number

Here's an example of how to use it:

main(!IO) :-
   solutions(even_member([513,242,18,355,12,4]),Pairs1),
   io.write(Pairs1,!IO).

Running this program result in the following output:

[4, 12, 18, 242]

Sunday, February 28, 2016

A couple of quick notes on Mercury #1

I'm trying to learn about Mercury programming language. Here's a quick list of things I learned recently about it.

Getting a Windows version of the Mercury compiler

I was able to get a version of the Mercury compiler by downloading a "Release of the day" version from here: http://dl.mercurylang.org/index.html.

I just followed the instructions from INSTALL file. The only requirement is to have a Cygwin version installed.

Operations are associated with a data type

For example the predicate for performing an operation N times is defined in the int module (int.fold_up, int_fold_down).

Predicates can be partially applied

Mercury supports a mechanism similar to currying in other languages.

For example, in the following invocation to int.fold_up we're not specifying values or variables for the last three arguments(these are resolved by the application inside int.fold_up):


:- pred write_pixel_data(
        io.binary_output_stream::in,
 array(int)::in,
        int::in,  % width
        int::in,  % height
        int::in,  % padding
        int::in,  % idx
        io::di, io::uo) is det.
.
.
.
int.fold_up(write_pixel_data(Stream,
            ImgData,
            Width * 3,
            Height,
            (RowWidth - (Width * 3))),0,(RowWidth*Height) - 1,!IO)

Bitwise operators look nice!

For example bitwise "and" look like:

   io.write_byte(Stream, (IntValue >> 8) /\ 0xFF,!IO), 

Code for this post can be found here

Sunday, October 18, 2015

Using traits to reuse code in Pharo

While working on a small Tetris-like clone in Pharo, I found an opportunity to reuse some code.

It's common for Tetris implementations to show a small preview of the tetrimino that comes next. Here's how it looks:

I wanted to create a separate Morphic component to show this preview. But I didn't want to duplicate the code required to paint the tetriminos. Sharing this code will allow me to have just one place to change the way tetriminos look. Also I didn't want to create a base class on top of both the game and the preview Morphs.

While reading about Pharo and Squeak I found that it supports Traits. The Pharo collaborActive book provides a nice explanation of how to use traits. Here's a quick definition from this document:

... traits are just groups of methods that can be reused in different classes.

This is exactly what I needed for reusing the tetrimino matrix drawing code. The following code shows the code defined in the game matrix Morph component.

drawOn: canvas
   "Draws the current game state"
   |rows columns currentValue rectangle currentColor cellWidth cellHeight|

   rows := gameState size x.
   columns := gameState size y.

   super drawOn: canvas.

   cellWidth :=   ((self width) / columns) asFloat truncated.
   cellHeight :=   ((self height) / rows) asFloat truncated.
   1 to: rows do: [ :row |
      1 to: columns do: [ :column|
         currentValue := gameState at: row at: column .
         currentValue ~= 0 ifTrue: [
                 currentColor := (colors at: currentValue).
                 rectangle := Rectangle left: (self bounds left)



                 canvas frameAndFillRectangle: rectangle
                                 fillColor:  currentColor
                                 borderWidth:  1
                                 borderColor: (Color white).
                  ]
          ]
       ].

Moving this code to a trait implies that I have to pass all instance state variables as an argument of the draw method.

The definition of the trait looks like this:

Trait named: #TTetriminoDrawing
    uses: {}
    category: 'TryTrix'

And the definition of the method inside this trait looks like this:

drawGameStateOn: canvas 
      width: areaWidth height: areaHeight 
      columns: columns rows: rows 
      morphBounds: morphBounds
      matrix: contentMatrix
      colors:  colorPalette
   "Draw the contents of the specified matrix on the given canvas"
   |cellWidth cellHeight currentValue currentColor rectangle|
      cellWidth :=   (areaWidth / columns) asFloat truncated.
   cellHeight :=   (areaHeight / rows) asFloat truncated.
   1 to: rows do: [ :row |
      1 to: columns do: [ :column|
         currentValue := contentMatrix at: row at: column .
         currentValue ~= 0 ifTrue: [ 
            currentColor := (colorPalette at: currentValue).
            rectangle := Rectangle left: (morphBounds left) + ((column - 1)*cellWidth) 
                                    right: (morphBounds left) + ((column - 1)*cellWidth) + cellWidth
                                    top: (morphBounds top) + ((row - 1)*cellHeight )
                                    bottom: (morphBounds top) + ((row - 1)*cellHeight ) + cellHeight.
            canvas frameAndFillRectangle: rectangle
                  fillColor:  currentColor
                  borderWidth:  1
                  borderColor: (Color white).
             ]
          ]
       ].

Now I can use this trait inside each morph definition:

Morph subclass: #TryTrixMorph
    uses: TTetriminoDrawing
    instanceVariableNames: 'gameState colors eventHandlers'
    classVariableNames: ''
    category: 'TryTrix'


Morph subclass: #TetriminoPreview
    uses: TTetriminoDrawing
    instanceVariableNames: 'matrix'
    classVariableNames: ''
    category: 'TryTrix'

This code can be found in here.

Tuesday, September 15, 2015

A small Tetris-like Morphic component in Pharo

As part of my exploration of Pharo, I wanted to create a small basic/naive/incomplete implementation of a Tetris-like game as a Morphic component. Here's an example of the current state of the code:

Implementation

The (still incomplete) implementation is very simple. It uses a matrix to represent the game state. When we want to paint the current game state, we examine the matrix and paint a small rectangle for each of the occupied positions.

drawOn: canvas
   "Draws the current game state"
   |rows columns currentValue rectangle currentColor cellWidth cellHeight|

   rows := gameState size x.
   columns := gameState size y.
   
   super drawOn: canvas.
   
   cellWidth :=   ((self width) / columns) asFloat truncated.
   cellHeight :=   ((self height) / rows) asFloat truncated.
   1 to: rows do: [ :row |
      1 to: columns do: [ :column|
         currentValue := gameState at: row at: column .
         currentValue ~= 0 ifTrue: [ 
            currentColor := (colors at: currentValue).
            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.
            canvas frameAndFillRectangle: rectangle
                  fillColor:  currentColor
                  borderWidth:  1
                  borderColor: (Color white).
             ]
          ]
       ].

Each Tetrimino is also represented as a small matrix.

Here's the definition for the 'J' and 'S' tetriminos:


   kind = #J ifTrue: [ 
      resultTetrimino := 
         Tetrimino 
            create: gameMatrix 
            tetriminoMatrix: 
               (Matrix rows: 2 
                  columns: 3 
                  contents: { 1. 1. 1.
                              0. 0. 1. })  
            colorIndex: 5.
      ].

...

   kind = #S ifTrue: [ 
      resultTetrimino := 
         Tetrimino 
            create: gameMatrix 
            tetriminoMatrix: 
               (Matrix rows: 2 
                  columns: 3 
                  contents: { 0. 1. 1.
                              1. 1. 0. })  
            colorIndex: 3.
      ].

The implementation is still incomplete, I hope that future posts will show more progress.

The source code can be found here: http://www.github.com/ldfallas/TryTrix .

Friday, August 28, 2015

Glider Gun

Just a quick look at the Gosper's Glider Gun pattern.

This is running on Pharo using this program https://github.com/ldfallas/GameOfLife

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"