Transcript

‘comments’. Remove the comments andthe recipe will still work. We need a clearway to show when a comment starts andends. We will start them with a specialsymbol ‘/*’ and end them with ‘*/’.

RECIPE Hummus and Tomato Pasta (){

/* Serves 2This is a very quick 20-minute afterwork dish.

*/…

}

Variable storage

What comes next in a recipe is usually alist of ingredients. The idea is to listeverything you need so you can have it allready before you start. I often have aproblem following recipes, though, as theydon’t list absolutely everything. Mid-recipe I might suddenly find I need afrying pan…when mine is crusted withburnt cheese sauce from last night! Toavoid that, let’s list all the pans we needtoo. For our recipe we need a frying panand a saucepan.

Something used to store things (like pansdo) in a program is called a ‘variable’.Program variables hold things likenumbers. The equivalent of theingredients list ‘declares’ the variables.Declarations give each variable a uniquename used to refer to it and also giveeach a ‘type’ – is it a saucepan or a fryingpan we need? To be clear about when adeclaration ends we add in somepunctuation. Programming languages tendto use a semicolon for that – it’s a bit likea full stop in English.

Saucepan pan1;Fryingpan pan2;

www.cs4fn.org14

Programmers are the master chefs of thecomputing world – except the recipes theyinvent don’t just give us a nice meal, theychange the way we live.

Programs are very similar to recipes. Theyboth give instructions that, if followed,achieve something. There is a differencebetween them, though, and it has to dowith language. When chefs invent recipesthey write them out in human languageslike English. Programmers write programsin special languages. Why’s that? It’s allabout being precise enough to be sureexactly the same thing happens everytime. Recipes are often ambiguous whichis why when I follow one it sometimesgoes wrong. Programs tie down every lastdetail.

Let’s apply some ideas from programminglanguages to making meals. One of myfavourite recipes is a hummus-basedpasta dish (see box) so we’ll use that.

Structure it!

The first thing to notice about a recipebook is there is a clear structure. Eachrecipe is obviously separate from theothers. Each has a title and a briefdescription of how it might be used. Eachhas an ingredients list and then a seriesof steps to follow. Programs follow asimilar structure.

Cookery books use page layout to showtheir structure. Programmers uselanguage: grammar, symbols andkeywords. A keyword is a word that meanssomething special. Once you havedecided a word is a keyword you only everuse it for that purpose.

Let’s invent a keyword RECIPE to meanwe’re starting a new recipe. The only timethat word will appear in our recipes is tostart a new recipe. What follows it willalways be the name of the recipe. We willalso need to know when the name ends.To make that clear we will use a specialsymbol made up of open and closebrackets ().

We also want to be absolutely sure what ispart of this recipe and what isn’t. We willuse curly brackets: everything betweenthe brackets is part of the named recipe.

RECIPE Hummus and Tomato Pasta (){

…}

No comment?

Recipes usually include a briefdescription that isn’t part of the actualinstructions. It is just there to helpsomeone understand when you might usethe recipe. Programs have descriptionslike this too. Programmers call them

How is a computer program like a recipe? Paul Curzon explains,and as a bonus, tells you how to cook a quick pasta dish.

A recipe forprogramming

Hummus andTomato PastaServes 2This is a very quick 20-minute after workdish.

Olive oil1 teaspoon of whole cumin seeds1 large chopped onion400g chopped plum tomatoes200g hummus150g pasta

1. Add the pasta to a large pan of boilingwater. Simmer for 10 minutes.

2. Fry the cumin in the olive oil for a fewminutes. Add the onions and frygently.

3. Stir in the tomatoes and the hummusand leave to simmer for 5 minutes.

4. Drain the pasta and serve.

This says that in the rest of the recipewhen we say pan1 (the variable name) wemean a particular pan: a saucepan (itstype). When we say pan2 we mean aparticular frying pan.

New assignment

We will make a distinction between thingsto hold stuff, like pans (variables) and theactual ingredients that go in them:‘values’. We will also follow the TV chefsand start by setting out all the ingredientsin little dishes at the start so they are athand – and make that part of theinstructions.

We will need to declare a dish to holdeach ingredient, giving its type and givingthe dish a name. At the same time we willsay what should be put in it before therecipe proper is started. We will use an ‘=’symbol to mean put something in avariable (i.e., dish or pan). In programs,this action of putting something in avariable is called ‘assignment’. So, forexample, we will declare that we need adish to hold the hummus (calledhummusDish). We assign 200g ofhummus to it.

Dish hummusDish = 200g hummus;

We are now ready for the recipe proper.We can use assignment as a precise wayof moving things from one place toanother too. So if we say, for example:

pan2 = oilDish;

We mean empty the contents of the dishof oil into the frying pan. Programs areslightly different here, as when they do anassignment they don’t move things fromone place to the other, they copy it. That would be like having a di sh thatautomatically refilled itself whenever itwas emptied.

Often we want to add to whatever isalready in a pan. Programmers leavenothing to doubt and say explicitly that is what they mean:

pan2 = pan2 + onionDish;

This tells us to mix what is in the oniondish with what is in the frying pan, andthen leave the result in the frying pan. Wewill use the + symbol to mean add togetherand stir. (continued on the next page)

cs4fn!eecs.qmul.ac.uk 15

Assignment does NOTmove things around,it makes new copies

www.cs4fn.org16

Methods in mymadness

So far all we’ve done is putingredients in things and copied themaround. To make a meal we need todo various basic cooking things likeheat a pan or drain a pan. Rather thanspell out every step of how you do thatin every recipe, we will use a shorthand. We create mini-recipes that sayhow to do it and just refer to them byname. They are often called ‘methods’by programmers. Each is written outjust like our recipe. In fact to aprogrammer our recipe is a methodtoo. When we want to use it we justgive its name followed by any extrainformation needed. For example toheat a pan, we need to know whichpan, how high a heat and for howlong. We write, for example:

Heat (pan1, medium, 12 minutes);

This format helps make sure we don’tmiss something (like the time forexample). We need similar methodsfor draining a pan and serving themeal. We won’t give the actualinstructions here. In a full programthey would be written down step-by-step too and not left to chance.

Time to do it right

We have come up with a language forrecipes similar to the ones used forprogramming. We’ve used symbols,keywords and very precise punctuation– the language’s ‘syntax’ – to help us

be precise. On its own that’s not enough –each part of the language has to have avery clear meaning too – the language’s‘semantics’. Together they make sure infollowing a recipe we know exactly whateach step involves. There is then less

scope for a cook (or computer) to get itwrong. Computers, of course, have nointelligence of their own. All they cando is exactly follow the instructionssomeone wrote for them (a bit like mecooking).

A recipe forprogramming(continued from page 15)

Here’s what our complete recipe looks like as a program.RECIPE Hummus and Tomato Pasta (){

/* Serves 2. This is a very quick after work dish. It only takes about 20 minutes from start to finish. */

Saucepan pan1;Fryingpan pan2;

/* Ingredients */ Dish oilDish = 1 tablespoon of olive oil;Dish cuminDish = 1 teaspoon of whole cumin seeds;

Dish onionDish = 1 large onion, chopped;Dish tomatoDish = 400g chopped plum tomatoes;Dish hummusDish = 200g hummus;

Dish pastaDish = 150g pasta;Kettle kettle = 500ml boiling water;

/* Cook the pasta */ pan1 = kettle + pastaDish;Heat (pan1, high, 2 minutes);Heat (pan1, medium, 10 minutes);

/* Make the sauce */ pan2 = oilDish + cuminDish;Heat (pan2, high, 2 minutes);

pan2 = pan2 + onionDish;Heat (pan2, medium, 5 minutes);

pan2 = pan2 + tomatoDish + hummusDish;Heat (pan2, low, 5 minutes);

/* serve */ Drain (pan1);Serve (pan1, pan2);

}


Recommended