Your SlideShare is downloading. ×
Logo tutorial
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Logo tutorial

647
views

Published on


0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
647
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
15
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Logo TutorialHistoryLogo was developed in the late 1960s at Bolt Beranek and Newman, Inc., inCambridge, MA by W. Feurzeig, D. Bobrow and S. Papert. Its purpose was to teachchildren to program. Its central feature is that it provides simple commands formoving a ``turtle on a surface. Initially the language was used to direct the motion ofa small robot that was dressed up to look like a turtle. It was placed on a sheet ofpaper and dragged a pen underneath it, thereby drawing figures on the paper. Todaythe ``turtle is a small arrow-like figure that moves on the screen of a computer.Underneath, Logo is very much like Lisp, the list-processing language used inArtificial Intelligence, the branch of computer science that tries to make machinesbehave intelligently. However, it also has features of other languages, includingPascal.The Logo EnvironmentThe Logo in use at Brown is Berkeley Logo. It can be activated by selecting it fromthe left Menu button. You will have to position a window on the screen. We will callit the command window. Another window will appear, possibly on top of thecommand window. If necessary, use the middle mouse button to move it (drag the topof the window) so you can see the command window again. A ? prompt is presentedin the comand window. At the prompt, commands can be issued that are executedimmediately. When a drawing command is issued, say, the command forward 10, agraphics window appears which must be positioned on the screen. The graphicswindow in this case shows an arrowhead (the turtle) with a line behind it that is 10units long. When other drawing commands are issued, such as rt 45 fd 60, the turtleturns right 45 degrees and then advances another 60 units. The command cs will clearthe screen and reposition the turtle at its center.Sometimes you will need to stop a Logo procedure. Do this with ^c (control c). Toexit logo, type bye in the command window.Logo the LanguageThis tutorial provides the rudiments of the language, enough to do the simpleassignments that are given in CS4. The commands that we explain are drawing
  • 2. commands, variables, arithmetic operators, and procedures, including recursiveprocedures.Drawing CommandsThe simple Logo drawing commands move the turtle forward and backward and turnit right or left. The commands and their abbreviations are given below: fd forward bk backward rt right lt left cs clearscreenEither version of these commands can be used.Each of these commands must be followed by one value called its argument. Thearguments for fd and bk are units; those of rt and lt are angles which can be anyinteger. Of course, a rotation by 360 is a complete rotation so a rotation by 375degrees is the same as one by 15 degrees.The graphics window has a coordinate system. The values of the two coordinates(normally called x and y) at the center are 0, 0. At the northeast corner they are 250,250; at the southeast corner, they are 250, -250; at the southwest corner, they are -250,-250; etc. If the turtle tries to walk off one side of the screen, it wraps around. Theright side wraps to the left side and the top wraps to the bottom.Now lets try some commands. Commands be issued one per line followed by acarriage return. Several of them can be typed in succession in a command windowfollowed by a carriage return. The effect on the turtle is the same. However, if youtype a command that requires one or more inputs and provide the missing input(s) onthe next line, Logo will complain.The commands fd 60 rt 120 fd 60 rt 120 fd 60 rt 120cause the turtle to draw a triangle, as you can see by trying them out. Thesecommands are read from left to right. Since the command fd requires one argument, itis taken as the next value. Similarly, rt takes one argument also. Thus, Logo can giveunambiguous meaning to each of these character strings. For some Logo commandsseparators are needed.
  • 3. In the above example, the commands fd 60 rt 120 are repeated three times. To savetime and space Logo provides the repeat command. The following command has thesame effect as those given in the above example. repeat 3 [fd 60 rt 120]The square brackets indicate that the enclosed commands are to be executed threetimes.Other Turtle Moving and Drawing CommandsLogo has a number of other drawing commands, including those shown below. pu penup pd pendown ht hideturtle st showturtle home label setxyThe pendown and penup commands tell the turtle to leave ink on the screen as itmoves or not leave ink, respectively. The hideturtle and showturtle commands hide orshow the turtle but do not affect its ability to leave ink as it moves. The homecommand causes the turtle to return to the center of the screen. It may leave inkbehind when it does this. These four commands do not take arguments. The labelcommand takes a single word as a quoted string (e.g. ``a_string) or a list of words in []brackets without quotation (e.g. [a string of letters]) and prints them on the graphicswindow at the location of the turtle. (Try them!) The command setxy takes twoarguments, treats the first as the value of the abscissa (horizontal axis) and the secondas a value of the ordinate (vertical axis). It places the turtle at these coordinates,possibly leaving ink as it does so.What kind of figure does the following command sequence produce? cs pu setxy -60 60 pd home rt 45 fd 85 lt 135 fd 120Interpret these commands as you read them from left to right.Logo VariablesA variable is the name of location that contains a value. In the random-access machineeach memory location has an integer address. Since it would be hard to remember theaddress of each location containing a value used by a program, computer scientists
  • 4. have found ways of given locations symbolic names. Once a variable has a name, wecan use and manipulate it.Variables are given names which are strings of letters, hence size could be the nameof a variable. When we wish to use the value of a variable in a computation, we referto it as :size. Note the use of the colon before the name of the variable. For example, ifsize has been given a value, then we can say fd :size and logo will move forward by anumber of units which is the value of the variable size.There are several ways to give a value to a variable. An explicit way to do this isdescribed below. An implicit way will be seen when we introduce procedures. Avariable can be given a value with the make command, as shown below. make "size 60This command gives size the value 60. Note that in this case we have used ``size,not :size. The reason is that :size is the value of the variable size, while ``size is itsname. We say that ``size is the ``quoted name of size. Logo tries to ``evaluate wordsas it reads them because some words are the names of procedures. We quote words totell Logo they should be not be evaluated.The make command gives a value to a variable even if it has not yet been used in aprogram. In this way Logo differs markedly from Pascal. In Pascal a variable mustfirst be given a type (``declared) such as integer, real, or character, before it can beused. In Logo variables do not have types nor do they have to be declared beforebeing used.As a digression, consider the command print. It is given one argument and it prints thevalue of the argument in the command window. Thus, the command print 50 will printthe integer 50. We introduce this command so that we can demonstrate another use ofquoted names. The cleartext command, abbreviated ct, clears the text region of thecommand window.Since quotation before a word means it should not be evaluated, the command print``hello should print the word hello in the command window. Does it?Now lets give the variable first_programmer a value which is the name of the firstprogrammer. Try executing the following commands in the command window. make "first_programmer "Ada_Lovelace print :first_programmer
  • 5. Note that we quote the name of the variable first_programmer in the make commandbut use the colon version to obtain its value. Ada_Lovelace is quoted so it isrecognized as string and not a variable. (Ada Lovelace was the first programmer.)Arithmetic OperationsLogo provides the usual arithmetic operations of addition, subtraction, multiplicationand division, denoted by the symbols +, -, *, /. Each of these operations produces aresult. If you dont do something with the result, Logo will complain. With the printcommand the result of an arithmetic operation can be used and printed in thecommand window. Try the following commands: make "size 81/9 print 2*3 print :size - 4Other useful commands are sqrt, which takes one non-negative argument and returnsits square root, power, which takes two arguments, call them a and b, and outputs a tothe b power, denoted ab, and ln, which takes one argument and returns its naturallogarithm. Other functions are exp, which takes one argument and computes e to thatpower, e the natural number 2.718281828, and log10, which takes the logarithm tobase 10 of its one argument. For other operations, see the complete manual. Try ln2.718281828. Whoops! Use print ln 2.718281828 instead.Try out these ideas with the following simple code make "angle 0 repeat 1000 [fd 3 rt :angle make "angle :angle + 7]The figure it produces is shown below.What are the successive values of the variable angle? How many blobs does itproduce? Suppose the integer 7 is changed to 11 or 13. How many blobs are producedin these cases?Arithmetic operators have precedences that determine the order with which they areevaluated. Note that print 60 * sqrt 2 and print sqrt 2 * 60 produce different answers.Here the * operator has precedence over the sqrt operator. Thus, * will be done beforesqrt if there is a choice, as there is in the second case. For this reason the firststatement prints the value of 60 times the square root of 2 whereas second prints thesquare root of 120.RandomizationSometimes it is fun to have the outcome of a computation be unpredictable. Logoprovides the random procedure to generate a random number. random has one
  • 6. argument and produces an integer value chosen uniformly at random between 0 andthe value of its argument. Thus, if you want a random angle between 1 and 360degrees, you could use the command random 360 to produce it. Bear in mind thatLogo will complain unless you do something with the result, such as print it. Try print random 360several times in the command window and see what it produces. For a little more fun,try repeat 100 [fd random 80 rt 90] repeat 1000 [fd 4 rt random 360]The first procedure produces a drawing such as that shown below. What does thesecond do?ProceduresProcedures provide a way to encapsulate a collection of commands. Once a procedurehas been created, it can be used just the way a built in command is used. The``meaning of a procedure is the meaning of its individual commands.A procedure without arguments has the word to (a reserved word) and the name of theprocedure on the first line. (Reserved words in Logo cannot be used as variables andhave a well-defined meaning and use.) It has the reserved word end on the last line.The procedure shown below encapsulates the next to the last set of instructions shownabove. Aft er writing it with the editor, invoke the procedure random_walk by typingit in the command window. to random_walk repeat 100 [fd random 80 rt 90] endThis is dramatic evidence that a procedure merely provides a name for a set ofcommands.Procedures can contain not only built in commands, they can also contain otherprocedures. For example, if you want to build a tree (see the figure on the next page)you will want to draw its trunk as well as its foliage. It is wise to begin experimentingwith a procedure to draw a trunk. When you are satisfied with the trunk procedure,you can then construct a foliage procedure. A trunk procedure can be constructedfrom procedures to draw the left side of the trunk, a second to draw the top, and athird to draw the right side of the trunk. To finish up, it is prudent to have a procedureto center the turtle on the top of the trunk. From this point a circle can be drawn forthe foliage. Through a series of experiments, we have constructed procedures of thiskind to draw the tree shown in the figure on the next page. The procedures producingthis drawing are given below.to left_side
  • 7. rt 20 fd 20 lt 20 fd 60endto top_sidert 90 fd 25 rt 90endto right_sidefd 60 lt 20 fd 20 rt 20endto return_startrt 90 fd 40rt 90endto trunkleft_sidetop_sideright_sidereturn_startendto center_toppufd 80
  • 8. rt 90fd 20lt 90pdendto circlerepeat 360 [fd 1 rt 1]endto treepu bk 100 pdtrunkcenter_topleft 90circleendYou are encouraged to experiment with these commands. Can you design a morerealistic foliage for the tree, perhaps by modifying the circle program so that it looks abit more ragged?Editing Your ProjectTo edit your project, you will use the Xemacs editor, which starts up when you log in.You can also start Xemacs from your left mouse button. Type your procedures intoyour emacs window. When you are ready to try them out, select "Save Buffer" fromthe "Files" menu, and save your file as /u/bridgexx/src-logo/Fractal/Fractal.logo,where bridgexx is your bridge account number. Then, in your logo window, type load"Fractal.logo to load your procedures into logos memory. When you make changes toyour file in emacs, you will need to save it and re-load it into the command window.
  • 9. Another, even stranger feature of the logo editor is that you cannot destroy proceduresonce you have created them by deleting these procedures from the editor file!Although it looks like your procedure is gone, it is still in logos memory. To tell logoto "un-know" that procedure, you need to type erase "procedurename in the commandwindow.Note: Comments can be inserted on any line of a Logo program, after a semicolon.Commenting programs is highly desirable at all times. The human mind is not able toremember the details of complicated tasks and needs help. Also, without comments, aperson who is not the author of a program is likely to find it much more difficult tounderstand and modify if the author did not properly comment it. See the fractal codebelow for examples.Procedure InvocationThere is a very simple rule to explain the meaning of a procedure that invokes otherprocedures, including itself. It is called the copy rule. When one procedure callsanother it has the same effect as if the second procedure were copied into the first.ControlThe repeat command provides control over the number of times an operation isperformed. It has two arguments, the number of times to repeat a list and the list itselfin brackets []. We also have the stop command which stops the execution of aprocedure when it is reached. Another important control command is the if command.It takes two arguments, a ``predicate and a list. A predicate is an expression thatevaluates to true or false. A predicate is constructed of two arguments and one of thecomparison operators <, > and =. Since they are ``infix operators they appearbetween two numerical arguments, e.g. :size < 3. The following is a typical use of theif command in our abbreviated introduction to Logo. if :size < 3 [stop]If the value of the variable size is less than 3, the procedure stops.Procedures with ParametersParameters make procedures much more useful. Following the procedure name on thefirst line any number of variables can be specified in the colon format, as illustratedbelow: to square :size repeat 4 [fd :size rt 90] endThis procedure draws a square. The length of each side is size. This procedure isinvoked by providing the procedure name and one parameter where the parameter is
  • 10. either an integer or an integer-valued variable, e.g. square 60 or square :side where:side is an integer-valued variable.The three procedure given below draw a crude house. The procedure house invokesthe procedures square and floor. to square :size repeat 4 [fd :size rt 90] ; where is the turtle when this stepcompletes? end to floor :size repeat 2 [fd :size rt 90 fd :size * 2 rt 90] end to house floor 60 fd 60 floor 60 ; where is the turtle at this point? pu fd 20 rt 90 fd 20 lt 90 pd square 20 pu rt 90 fd 60 lt 90 pd square 20 endRecursive ProceduresWhen a procedure invokes a copy of itself, it said to be recursive. The meaning ofrecursive procedures is obtained in exactly the same way as regular proceduralinvocation, namely, via the copy rule. An example of a recursive procedure is givenbelow. BEWARE. This procedure will run indefinitely. You will need to rememberhow to stop a running procedure from the command window, namely, with ^c onUnix machines (Command . on Macs). to star to walk_the_stars repeat 5 [fd 10 rt 144] fd 20 rt random 360 end star walk_the_stars endExperiment with the procedure star to see what it does. The procedure walk_the_starsmoves 20 units, turns right by a random angle between 1 and 360, draws the star, andthen calls itself. By the copy rule, it will repeat these operations indefinitely, that is, itnever stops. It is for this reason that you must know how to stop Logo. This proceduredoes not tell Logo to stop.Another illustration of recursion is given below. In this case, the procedure fractal willterminate. It is shown alongside a procedure to draw a triangle. If you look closely,
  • 11. you will see that is formed from the triangle procedure by drawing a copy of a smallerversion of itself along each side of the triangle. Such figures are called fractalsbecause they have the self-similar property; they look the same at every degree ofmagnification. (In this case, the magnification cannot be unlimited because the figureis finite.) This particular fractal is called Serpienskis Gasket. It is very pretty. to triangle :size to fractal :size repeat 3 [fd :size rt 120] if :size < 3 [stop] ; the procedure stops if size is too small end repeat 3 [fd :size fractal :size/2 fd :size rt 120] endTo run fractal, type fractal 60 (or fractal x for some other integer x) in the commandwindow.Logo TutorialTelling Logo Where To GoGetting Logo to move around is easy, just tell him where to go and hell do it. Logoalways looks in a special place for instructions. That place is the first line insidethe main procedure. Press the Load Code button to load the code provided for you intothe pane on the right side of your Logo Application window. At the top of your screenyoull see this: procedure main endPut the instructions you want Logo to follow below procedure main and above end.To get started, youll need just three simple instructions. The first instruction, go, isyour way of telling Logo to walk forward in the direction hes facing. To get Logo towalk forward 50 steps, type go 50. Remember to type this inside the main procedure.Press the draw button and watch Logo walk forward 50 steps.
  • 12. The other two instructions, rt and lt tell Logo which way to turn and how much. Forexample, to make Logo turn right 90 degrees, type rt 90. If you dont remember howdegrees work, take a look at this explanation.The MazeYour first challenge is to get Logo out of the maze. Use the Load Maze button on yourLogoApplication to draw the maze. Now use the instructions you just learned, go, rt,and lt to get Logo out of the maze. Let us know if you need help or hints.AnimationLogo moves so fast that you really cant see him move, you can only tell where hesbeen by the line he draws as he moves. To slow Logo down enough that you can seehim moving, we wrote a procedure, logo. It is one of the procedures that was loadedwhen you pressed the Load Code button. You can use logo instead ofgo to tell Logo tomove slowly. To tell Logo to take 50 steps, slowly, type goto logo, steps = 50.Unfortunately, on some of your computers the screen will flicker a lot when Logomoves slowly. What can we say, animation is tricky.SyntaxSome of you may have experienced problems by now. If you forgot to put yourinstructions inside the main procedure then you got an error. Also, every computerlanguage requires you to follow very precise rules when writing instructions. Theserules are known as the syntax of the language. If you do not follow theserulesprecisely Logo will not be able to underestand your instructions.So far, youve used four Logo commands. The first three commands, go, rt and lt justtell Logo how to move. The fourth, goto, allows you to call a procedure.Calling ProceduresThe syntax for calling procedures is:goto procedure name, parameter = valueIn goto logo, steps = 50 • procedure name is logo • parameter is steps
  • 13. • value is 50.Some procedures have no parameters, so the syntax for calling them is just:goto procedure nameOther procedures have two parameters, and the syntax for calling them is:goto procedure name, parameter1 = value1, parameter2 = value2Can you figure out what the syntax for calling a procedure that has three parameterswould be?Write Your Own ProcedureYou can make procedures of your own if you want. The syntax for any procedure isthe same as that for the main procedure:procedure procedure name procedure bodyendIn the main procedure you just wrote, • procedure name is main • procedure body is the code you wrote to get Logo out of the mazeDo not call your procedure main; main is a special word reserved for the mainprocedure.Try writing a procedure to draw a simple shape: a square or a triangle or a rectangle.This is an example of a procedure to draw a pentagon (a five-sided figure).procedure pentagon goto logo, steps = 50 rt 360/5 goto logo, steps = 50 rt 360/5 goto logo, steps = 50 rt 360/5 goto logo, steps = 50 rt 360/5 goto logo, steps = 50 rt 360/5end
  • 14. Notice that Logo can do simple math; instead of bothering to calculate 360/5 formyself, I let Logo do it.Also, I used the logo procedure because I wanted Logo tomove slowly. If you want Logo to move rapidly, use the go command instead. Goahead and call your procedure inside your main method. Use the Clear button to getrid of the maze.Parameterize Your ProcedureThe pentagon procedure is nice, but it could be better. Right now, it only makes onesize of pentagon, one where Logo takes 50 steps on each side. If I make the number ofsteps that Logo takes a parameter of the procedure, then I can use the same procedureto draw pentagons of any size.procedure pentagon goto logo, steps = side rt 360/5 goto logo, steps = side rt 360/5 goto logo, steps = side rt 360/5 goto logo, steps = side rt 360/5 goto logo, steps = side rt 360/5endThe new procedure uses the variable, side for the number of steps, instead of thenumber 50. Now, if I want Logo to draw a really small pentagon, I call pentagonlikethis: goto pentagon, side = 10. If I want Logo to draw a really large pentagon, Icall pentagon like this: goto pentagon, side=200. Of course, if Logo tries do draw apentagon that big, he might walk right off the drawing space. Can you parameterizeyour procedure in the same way?More Logo InstructionsLogo commands are the fundamental building blocks of the Logo language. So far,youve used just four commands, go, rt, and lt and the goto command for calling aprocedure. Press the Logo Syntax button in LogoApplication to see the othercommands you can use.The repeat command is very powerful. You can use this command to call a proceduremany times. These two procedures use repeat to draw a spiral. These procedures were
  • 15. also loaded when you pressed the Load Code button. Try calling spiral from yourmain procedure. Feel free to change spiral orspiralhelper and see how that changeswhat Logo does. procedure spiralhelper goto logo, steps = loop rt 50 end procedure spiral repeat 100, spiralhelper endFinishing UpDo you want to save a procedure you wrote so you can use it later? To do that, openthe Notepad application on your computer, copy the procedure into a Notepaddocument, and save it to the EYH folder on your Desktop. Name thefile your_name_here.logo. Well post your procedure on the main page so that you canaccess it anytime you want.