6 Tutorial 5 (Optional): The Pictures DSL
6.1 Step 1: The Pictures Example
A major benefit of functional programming is that we often get a description which closely resembles natural or mathematical language as we would use it in a textbook or report. Functional languages are often used to define domain-specific languages (DSL), which support simple and intuitive definition of problems and solutions within a specific domain. Simon Thompson gives a simple example in the Pictures module, which gives a simple DSL for image operations.
- 1.
- Download the source code for the textbook. You can do this on the commandline using:
wget https://hackage.haskell.org/package/Craft3e−0.1.0.10/Craft3e−0.1.0.10.tar.gz
- 2.
- Unpack the tarball.
tar xzf Craft3e−0.1.0.10.tar.gz
- 3.
- Unpacking the tarball gives you a new directory with all the source code for the textbook. Change
into this directory:
cd Craft3e−0.1.0.10
- 4.
- Use the following command to see the contents of the directory.
ls
Don’t worry about all the different files. We are really only interested in Pictures.hs.
- 5.
- Start
ghci
inside the Craft3e directory - 6.
- Load the Pictures module
:load Pictures
Note that the .hs extension is not required.
- 7.
- Print (render) the horse image as ASCII graphics
printPicture horse
Does it look like a horse? - 8.
- Try the standard
print
function too:print horse
This shows the raw data representing the image. You see a list of strings, each string enclosed in double quotes, and the list enclosed in square brackets with commas to separate the elements.
We will use the Pictures module for several exercises later.
6.2 Step 2: Pictures with SVG rendering
The ASCII arts used above isn’t too pleasing to the eye. There is a variation rendering SVG graphics as well, namely the PicturesSVG module. It requires a browser on the side for the display. Test it, and see that it works.
- 1.
- Make sure that Craft3e-0.1.0.10 is the current directory.
- 2.
- Open the file refresh.html in a web browser, e.g.
firefox refresh.html &
The ampersand (&) makes the program start in the background, so that it does not block the command prompt. - 3.
- Start ghci and load the PicturesSVG module. You can do this in two steps, as with the Pictures
module above, or you can do both in a single step giving the module name as an argument to
ghci:
ghci PicturesSVG
- 4.
- Render the horse picture
render horse
- 5.
- Take each of the images which you printed in ASCII in the previous step, and render them as SVG.
6.3 Step 3: Playing with Pictures
Do Exercises 2.1-2.4 in Simon Thompson’s book.
6.4 Step 4: Designing Problems
Do Exercises 4.25-4.30 in Simon Thompson’s book.