Restart by Jason Fried & David Heinemeier Hans is Business & Personal Finance # Světový i český album # Základní kniha pro maličké, malé i. Converting a web page to PDF is very easy to do! Once you've converted HTML content to PDF and saved it to iBooks, you can print it out. The PDF versions of this book are generated from the in-built PDF generation capabilities found in Open Office. Stop and restart the server.
|Language:||English, Spanish, Dutch|
|Distribution:||Free* [*Register to download]|
restarts and at an interval set by the system. In order . controlling the device ( e.g. restarting processes) is im- products/video/ruthenpress.info (/10/30), July . 1. ruthenpress.info PDF brought to you by generated on November 25, Chapter 2: Symfony2 versus Flat PHP | asks Wilkins for permission to restart. DNA model building, , ban on Watson and Crick working on. DNA, 95–99, 95–98 base ratios, thinking about the.
As it turns out, the process of learning to program is an excellent opportunity to practice problem-solving skills. On another level, you will use programming as a means to an end. As we go along, that end will become clearer. What Is a Program? A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching for and replacing text in a document, or something graphical, like processing an image or playing a video.
The details look different in different languages, but a few basic instructions appear in just about every language: Input Get data from the keyboard, a file, the network, or some other device. Output Display data on the screen, save it in a file, send it over the network, etc. Math Perform basic mathematical operations like addition and multiplication.
Conditional execution Check for certain conditions and run the appropriate code. Repetition Perform some action repeatedly, usually with some variation. So you can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions. Running Julia One of the challenges of getting started with Julia is that you might have to install it and related software on your computer.
If you are familiar with your operating system, and especially if you are comfortable with the command-line interface, you will have no trouble installing Julia. But for beginners, it can be painful to learn about system administration and programming at the same time. To avoid that problem, I recommend that you start out running Julia in a browser. In the browser, you can run Julia on JuliaBox. No installation is required—just point your browser there, log in, and start computing see JuliaBox.
But you should check that the version number is at least 1. The last line is a prompt that indicates that the REPL is ready for you to enter code. It displays a result on the screen. The parentheses indicate that println is a function.
Julia provides operators, which are symbols that represent computations like addition and multiplication. Some values we have seen so far are 2, These values belong to different types: 2 is an integer, What about values like "2" and " They look like numbers, but they are in quotation marks like strings. Julia parses 1,, as a comma-separated sequence of integers. They were not designed by people although people try to impose some order on them ; they evolved naturally.
Formal languages are languages that are designed by people for specific applications. For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols. Chemists use a formal language to represent the chemical structure of molecules. And most importantly, programming languages are formal languages that have been designed to express computations. Formal languages tend to have strict syntax rules that govern the structure of statements.
Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements. The second type of syntax rule pertains to the way tokens are combined. Similarly, in a chemical formula the subscript comes after the element name, not before. This sentence all valid tokens has, but invalid structure with. When you read a sentence in English or a statement in a formal language, you have to figure out the structure although in a natural language you do this subconsciously.
This process is called parsing. Although formal and natural languages have many features in common—tokens, structure, and syntax—there are some differences: Ambiguity Natural languages are full of ambiguity, which people deal with by using contextual clues and other information.
Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context. Redundancy In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose.
Formal languages are less redundant and more concise. Literalness Natural languages are full of idiom and metaphor. Formal languages mean exactly what they say. Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages.
The difference between formal and natural language is like the difference between poetry and prose, but more so: Poetry Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response.
Ambiguity is not only common but often deliberate. Prose The literal meaning of words is more important, and the structure contributes more meaning.
Prose is more amenable to analysis than poetry but still often ambiguous. Programs The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure.
Formal languages are more dense than natural languages, so it takes longer to read them. Also, the structure is important, so it is not always best to read from top to bottom, left to right. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language.
Debugging Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging. Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed. There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people.
One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture. Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively. Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming.
At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help! Glossary The process of formulating a problem, finding a solution, and expressing it.
REPL A program that repeatedly reads input, executes it, and outputs results. The types we have seen so far are integers Int64 , floating-point numbers Float64 , and strings String. All programming languages are formal languages. Exercises Tip It is a good idea to read this book in front of a computer so you can try out the examples as you go. Exercise Whenever you are experimenting with a new feature, you should try to make mistakes. What if you leave out both?
What if you spell println wrong? This kind of experiment helps you remember what you read; it also helps when you are programming, because you get to know what the error messages mean.
It is better to make mistakes now and on purpose rather than later and accidentally. In a print statement, what happens if you leave out one of the parentheses, or both? If you are trying to print a string, what happens if you leave out one of the quotation marks, or both? You can use a minus sign to make a negative number like What happens if you put a plus sign before a number?
In math notation, leading zeros are okay, as in What happens if you try this in Julia? What happens if you have two values with no operator between them? How many seconds are there in 42 minutes 42 seconds? How many miles are there in 10 kilometers? Tip There are 1. If you run a kilometer race in 37 minutes 48 seconds, what is your average pace time per mile in minutes and seconds?
What is your average speed in miles per hour? Variables, Expressions and Statements One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. A common way to represent variables on paper is to write the name with an arrow pointing to its value. Formal languages are languages that are designed by people for specific applications.
For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols.
Chemists use a formal language to represent the chemical structure of molecules. And most importantly, programming languages are formal languages that have been designed to express computations. Formal languages tend to have strict syntax rules that govern the structure of statements. Syntax rules come in two flavors, pertaining to tokens and structure. Tokens are the basic elements of the language, such as words, numbers, and chemical elements.
The second type of syntax rule pertains to the way tokens are combined. Similarly, in a chemical formula the subscript comes after the element name, not before. This sentence all valid tokens has, but invalid structure with.
When you read a sentence in English or a statement in a formal language, you have to figure out the structure although in a natural language you do this subconsciously.
This process is called parsing. Although formal and natural languages have many features in common—tokens, structure, and syntax—there are some differences:. Natural languages are full of ambiguity, which people deal with by using contextual clues and other information.
Formal languages are designed to be nearly or completely unambiguous, which means that any statement has exactly one meaning, regardless of context. In order to make up for ambiguity and reduce misunderstandings, natural languages employ lots of redundancy. As a result, they are often verbose. Formal languages are less redundant and more concise.
Natural languages are full of idiom and metaphor. Formal languages mean exactly what they say. Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages. The difference between formal and natural language is like the difference between poetry and prose, but more so:.
Words are used for their sounds as well as for their meaning, and the whole poem together creates an effect or emotional response. Ambiguity is not only common but often deliberate. The literal meaning of words is more important, and the structure contributes more meaning.
Prose is more amenable to analysis than poetry but still often ambiguous. The meaning of a computer program is unambiguous and literal, and can be understood entirely by analysis of the tokens and structure. Formal languages are more dense than natural languages, so it takes longer to read them.
Also, the structure is important, so it is not always best to read from top to bottom, left to right. Finally, the details matter. Small errors in spelling and punctuation, which you can get away with in natural languages, can make a big difference in a formal language. Programmers make mistakes. For whimsical reasons, programming errors are called bugs and the process of tracking them down is called debugging. Programming, and especially debugging, sometimes brings out strong emotions.
If you are struggling with a difficult bug, you might feel angry, despondent, or embarrassed. There is evidence that people naturally respond to computers as if they were people. When they work well, we think of them as teammates, and when they are obstinate or rude, we respond to them the same way we respond to rude, obstinate people. Preparing for these reactions might help you deal with them.
One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture. Your job is to be a good manager: And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.
Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming.
At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help! A symbol that represents a simple computation like addition, multiplication, or string concatenation. A category of values. The types we have seen so far are integers Int64 , floating-point numbers Float64 , and strings String. Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs.
All programming languages are formal languages. One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language. It is a good idea to read this book in front of a computer so you can try out the examples as you go.
Whenever you are experimenting with a new feature, you should try to make mistakes. What if you leave out both? What if you spell println wrong? This kind of experiment helps you remember what you read; it also helps when you are programming, because you get to know what the error messages mean. It is better to make mistakes now and on purpose rather than later and accidentally.
If you are trying to print a string, what happens if you leave out one of the quotation marks, or both? You can use a minus sign to make a negative number like What happens if you put a plus sign before a number?
In math notation, leading zeros are okay, as in What happens if you try this in Julia? If you run a kilometer race in 37 minutes 48 seconds, what is your average pace time per mile in minutes and seconds? What is your average speed in miles per hour? One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value.
This example makes three assignments. A common way to represent variables on paper is to write the name with an arrow pointing to its value. State diagram shows the result of the previous example.
Programmers generally choose names for their variables that are meaningful—they document what the variable is used for. Variable names can be as long as you like.
It is legal to use uppercase letters, but it is conventional to use only lower case for variable names. The REPL uses keywords to recognize the structure of the program, and they cannot be used as variable names. An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:. When you type an expression at the prompt, the REPL evaluates it, which means that it finds the value of the expression.
A statement is a unit of code that has an effect, like creating a variable or displaying a value. The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n.
When you type a statement, the REPL executes it, which means that it does whatever the statement says. Interactive mode is a good way to get started, but if you are working with more than a few lines of code, it can be clumsy.
The alternative is to save code in a file called a script and then run Julia in script mode to execute the script. By convention, Julia scripts have names that end with. If you know how to create and run a script on your computer, you are ready to go. Otherwise I recommend using JuliaBox again. Open a text file, write the script and save with a. Because Julia provides both modes, you can test bits of code in interactive mode before you put them in a script.
But there are differences between interactive mode and script mode that can be confusing. The first line assigns a value to miles and displays the value. The second line is an expression, so the REPL evaluates it and displays the result. It turns out that a marathon is about 42 kilometers. But if you type the same code into a script and run it, you get no output at all.
In script mode an expression, all by itself, has no visible effect. A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute. Now put the same statements in a script and run it. What is the output? Modify the script by transforming each expression into a print statement and then run it again. When an expression contains more than one operator, the order of evaluation depends on the operator precedence.
For mathematical operators, Julia follows mathematical convention. P arentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. M ultiplication and D ivision have higher precedence than A ddition and S ubtraction.
Operators with the same precedence are evaluated from left to right except exponentiation. For example:. If one of the values is a string, the other has to be an integer. As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These notes are called comments , and they start with the symbol:.
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:. Everything from the to the end of the line is ignored—it has no effect on the execution of the program. Comments are most useful when they document non-obvious features of the code. It is reasonable to assume that the reader can figure out what the code does; it is more useful to explain why. Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff.
Three kinds of errors can occur in a program: It is useful to distinguish between them in order to track them down more quickly. If there is a syntax error anywhere in your program, Julia displays an error message and quits, and you will not be able to run the program.
During the first few weeks of your programming career, you might spend a lot of time tracking down syntax errors. As you gain experience, you will make fewer errors and find them faster. The second type of error is a runtime error, so called because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional and bad has happened.
Runtime errors are rare in the simple programs you will see in the first few chapters, so it might be a while before you encounter one. If there is a semantic error in your program, it will run without generating error messages, but it will not do the right thing.
It will do something else. Specifically, it will do what you told it to do. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing. A reserved word that is used to parse a program; you cannot use keywords like if , function , and while as variable names. A section of code that represents a command or action. So far, the statements we have seen are assignments and print statements.
Rules governing the order in which expressions involving multiple mathematical operators and operands are evaluated. Information in a program that is meant for other programmers or anyone reading the source code and has no effect on the execution of the program. Repeating my advice from the previous chapter, whenever you learn a new feature, you should try it out in interactive mode and make errors on purpose to see what goes wrong.
In some languages every statement ends with a semi-colon, ;. What happens if you put a semi-colon at the end of a Julia statement?
In math notation you can multiply x and y like this: What happens if you try that in Julia? What about 5x? What is the volume of a sphere with radius 5? What is the total wholesale cost for 60 copies? If I leave my house at 6: In the context of programming, a function is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements.
The name of the function is println. The expression in parentheses is called the argument of the function. The result is also called the return value. Julia provides functions that convert values from one type to another. The parse function takes a string and converts it to any number type, if it can, or complains otherwise:. This second example finds the sine of radians.
The name of the variable is a hint that sin and the other trigonometric functions cos , tan , etc. If you know trigonometry, you can check the previous result by comparing it to the square root of two divided by two:. So far, we have looked at the elements of a program—variables, expressions, and statements—in isolation, without talking about how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of expression, including arithmetic operators:.
Almost anywhere you can put a value, you can put an arbitrary expression, with one exception: Any other expression on the left side is a syntax error we will see exceptions to this rule later. So far, we have only been using the functions that come with Julia, but it is also possible to add new functions. A function definition specifies the name of a new function and the sequence of statements that run when the function is called. Here is an example:. The name of the function is printlyrics.
The rules for function names are the same as for variable names: The first line of the function definition is called the header ; the rest is called the body. The body is terminated with the keyword end and it can contain any number of statements.
For readability the body of the function should be indented. Once you have defined a function, you can use it inside another function. For example, to repeat the previous refrain, we could write a function called repeatlyrics:. Pulling together the code fragments from the previous section, the whole program looks like this:. This program contains two function definitions: Function definitions get executed just like other statements, but the effect is to create function objects.
The statements inside the function do not run until the function is called, and the function definition generates no output. As you might expect, you have to create a function before you can run it.
In other words, the function definition has to run before the function gets called. Move the last line of this program to the top, so the function call appears before the definitions. Run the program and see what error message you get. Now move the function call back to the bottom and move the definition of printlyrics after the definition of repeatlyrics.
What happens when you run this program? To ensure that a function is defined before its first use, you have to know the order statements run in, which is called the flow of execution. Execution always begins at the first statement of the program. Statements are run one at a time, in order from top to bottom. A function call is like a detour in the flow of execution.
Instead of going to the next statement, the flow jumps to the body of the function, runs the statements there, and then comes back to pick up where it left off. That sounds simple enough, until you remember that one function can call another. While in the middle of one function, the program might have to run the statements in another function.
Then, while running that new function, the program might have to run yet another function! Fortunately, Julia is good at keeping track of where it is, so each time a function completes, the program picks up where it left off in the function that called it. When it gets to the end of the program, it terminates. Sometimes it makes more sense if you follow the flow of execution. Some of the functions we have seen require arguments. For example, when you call sin you pass a number as an argument.
Some functions take more than one argument: Inside the function, the arguments are assigned to variables called parameters.
Here is a definition for a function that takes an argument:. This function assigns the argument to a parameter named bruce. When the function is called, it prints the value of the parameter whatever it is twice. The same rules of composition that apply to built-in functions also apply to programmer-defined functions, so we can use any kind of expression as an argument for printtwice:.
The name of the variable we pass as an argument michael has nothing to do with the name of the parameter bruce. When you create a variable inside a function, it is local , which means that it only exists inside the function. This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:. When cattwice terminates, the variable concat is destroyed. If we try to print it, we get an exception:. Parameters are also local. For example, outside printtwice , there is no such thing as bruce.
To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to. Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it.
The stack diagram for the previous example is shown in Stack diagram. The frames are arranged in a stack that indicates which function called which, and so on. In this example, printtwice was called by cattwice , and cattwice was called by Main , which is a special name for the topmost frame.
When you create a variable outside of any function, it belongs to Main. Each parameter refers to the same value as its corresponding argument. So, part1 has the same value as line1 , part2 has the same value as line2 , and bruce has the same value as concat.
If an error occurs during a function call, Julia prints the name of the function, the name of the function that called it, and the name of the function that called that , all the way back to Main. For example, if you try to access concat from within printtwice , you get a UndefVarError:. This list of functions is called a stacktrace. It tells you what program file the error occurred in, and what line, and what functions were executing at the time.
It also shows the line of code that caused the error. The order of the functions in the stacktrace is the inverse of the order of the frames in the stack diagram. The function that is currently running is at the top. Some of the functions we have used, such as the math functions, return results; for lack of a better name, I call them fruitful functions. They are called void functions. When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:.
But in a script, if you call a fruitful function all by itself, the return value is lost forever! If you assign the result to a variable, you get a special value called nothing. To print the value nothing , you have to use the function show which is like print but can handle the value nothing.
The value nothing is not the same as the string "nothing". It is a special value that has its own type:. The functions we have written so far are all void. We will start writing fruitful functions in a few chapters. It may not be clear why it is worth the trouble to divide a program into functions.
There are several reasons:. Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug. Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place. Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it. One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming. In some ways debugging is like detective work. You are confronted with clues and you have to infer the processes and events that led to the results you see.
Debugging is also like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again. If your hypothesis was correct, you can predict the result of the modification, and you take a step closer to a working program.
If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out,. When you have eliminated the impossible, whatever remains, however improbable, must be the truth. For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a working program and make small modifications, debugging them as you go.
For example, Linux is an operating system that contains millions of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel chip.
This later evolved to Linux. A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result. A statement that creates a new function, specifying its name, parameters, and the statements it contains. A value created by a function definition.
The name of the function is a variable that refers to a function object. A statement that runs a function. It consists of the function name followed by an argument list in parentheses. A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function. The result of a function. If a function call is used as an expression, the return value is the value of the expression.
Using an expression as part of a larger expression, or a statement as part of a larger statement. A graphical representation of a stack of functions, their variables, and the values they refer to. A box in a stack diagram that represents a function call. It contains the local variables and parameters of the function. These exercises should be done using only the statements and other features we have learned so far. Write a function named rightjustify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
Use string concatenation and repetition. Also, Julia provides a built-in function called length that returns the length of a string, so the value of length "monty" is 5. A function object is a value you can assign to a variable or pass as an argument. For example, dotwice is a function that takes a function object as an argument and calls it twice:.
Modify dotwice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument. Use the modified version of dotwice to call printtwice twice, passing "spam" as an argument.
Define a new function called dofour that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.
The output from the next print statement would begin on the next line.
This chapter presents a case study that demonstrates a process for designing functions that work together. It introduces turtle graphics, a way to create programmatic drawings. Turtle graphics are not included in the Standard Library, so the ThinkJulia module has to be added to your Julia setup. The examples in this chapter can be executed in a graphical notebook on JuliaBox, which combines code, formatted text, math, and multimedia in a single document see JuliaBox.
A module is a file that contains a collection of related functions. Julia provides some modules in its Standard Library. Additional functionality can be added from a growing collection of packages https: Before we can use the functions in a module, we have to import it with an using statement:.
The ThinkJulia module provides a function called Turtle that creates a Luxor. Once you create a turtle, you can call a function to move it around a drawing.
For example, to move the turtle forward:. The svg keyword runs a macro that draws a SVG picture. Macros are an important but advanced feature of Julia. The arguments of forward are the turtle and a distance in pixels, so the actual size depends on your display. Another function you can call with a turtle as argument is turn for turning. The second argument for turn is an angle in degrees. Also, each turtle is holding a pen, which is either down or up; if the pen is down, the turtle leaves a trail when it moves.
Moving the turtle forward shows the trail left behind by the turtle. This is the simplest use of the for statement; we will see more later. But that should be enough to let you rewrite your square-drawing program.
The syntax of a for statement is similar to a function definition. It has a header and a body that ends with the keyword end. The body can contain any number of statements. A for statement is also called a loop because the flow of execution runs through the body and then loops back to the top. In this case, it runs the body four times. This version is actually a little different from the previous square-drawing code because it makes another turn after drawing the last side of the square.
The extra turn takes more time, but it simplifies the code if we do the same thing every time through the loop. This version also has the effect of leaving the turtle back in the starting position, facing in the starting direction. The following is a series of exercises using turtles.
They are meant to be fun, but they have a point, too. While you are working on them, think about what the point is. Write a function called square that takes a parameter named t , which is a turtle.
It should use the turtle to draw a square. Write a function call that passes t as an argument to square , and then run the macro again. Add another parameter, named len , to square. Modify the body so length of the sides is len , and then modify the function call to provide a second argument.
Run the macro again. Test with a range of values for len. Make a copy of square and change the name to polygon. Write a function called circle that takes a turtle, t , and radius, r , as parameters and that draws an approximate circle by calling polygon with an appropriate length and number of sides. Test your function with a range of values of r. Make a more general version of circle called arc that takes an additional parameter angle , which determines what fraction of a circle to draw.
The first exercise asks you to put your square-drawing code into a function definition and then call the function, passing the turtle as a parameter. Here is a solution:.
The innermost statements, forward and turn are indented twice to show that they are inside the for loop, which is inside the function definition. Wrapping a piece of code up in a function is called encapsulation.
One of the benefits of encapsulation is that it attaches a name to the code, which serves as a kind of documentation. Another advantage is that if you re-use the code, it is more concise to call a function twice than to copy and paste the body! Adding a parameter to a function is called generalization because it makes the function more general: The next step is also a generalization. Instead of drawing squares, polygon draws regular polygons with any number of sides.
The next step is to write circle , which takes a radius, r , as a parameter. Here is a simple solution that uses polygon to draw a sided polygon:. Thus, polygon draws a sided polygon that approximates a circle with radius r. One limitation of this solution is that n is a constant, which means that for very big circles, the line segments are too long, and for small circles, we waste time drawing very small segments.
One solution would be to generalize the function by taking n as a parameter. This would give the user whoever calls circle more control, but the interface would be less clean. The interface of a function is a summary of how it is used: What does the function do? And what is the return value? In this example, r belongs in the interface because it specifies the circle to be drawn. Rather than clutter up the interface, it is better to choose an appropriate value of n depending on circumference:.
When I wrote circle , I was able to re-use polygon because a many-sided polygon is a good approximation of a circle. One alternative is to start with a copy of polygon and transform it into arc. The result might look like this:. We could generalize polygon to take an angle as a third argument, but then polygon would no longer be an appropriate name! This process—rearranging a program to improve interfaces and facilitate code re-use—is called refactoring.
Once you start coding, you understand the problem better. Sometimes refactoring is a sign that you have learned something. A development plan is a process for writing programs.
The steps of this process are:. Once you get the program working, identify a coherent piece of it, encapsulate the piece in a function and give it a name. Repeat steps 1—3 until you have a set of working functions. Copy and paste working code to avoid retyping and re-debugging. Look for opportunities to improve the program by refactoring. For example, if you have similar code in several places, consider factoring it into an appropriately general function.
This approach lets you design as you go along. Documentation can be accessed in the REPL or in a notebook by typing? Docstrings are often triple-quoted strings, also known as multiline strings because the triple quotes allow the string to span more than one line.
A docstring contains the essential information someone would need to use this function. It explains concisely what the function does without getting into the details of how it does it. It explains what effect each parameter has on the behavior of the function and what type each parameter should be if it is not obvious. Writing this kind of documentation is an important part of interface design. A well-designed interface should be simple to explain; if you have a hard time explaining one of your functions, maybe the interface could be improved.
An interface is like a contract between a function and a caller. The caller agrees to provide certain parameters and the function agrees to do certain work. For example, polyline requires four arguments: These requirements are called preconditions because they are supposed to be true before the function starts executing. Conversely, conditions at the end of the function are postconditions.
Postconditions include the intended effect of the function like drawing line segments and any side effects like moving the turtle or making other changes. Preconditions are the responsibility of the caller. If the caller violates a properly documented! If the preconditions are satisfied and the postconditions are not, the bug is in the function.
If your pre- and postconditions are clear, they can help with debugging. The process of replacing something unnecessarily specific like a number with something appropriately general like a variable or parameter.
A description of how to use a function, including the name and descriptions of the arguments and return value. The process of modifying a working program to improve function interfaces and other qualities of the code. You can do the arithmetic by hand or add print statements to the code. The version of arc in Refactoring is not very accurate because the linear approximation of the circle is always outside the true circle. As a result, the turtle ends up a few pixels away from the correct destination.
My solution shows a way to reduce the effect of this error. Read the code and see if it makes sense to you. If you draw a diagram, you might see how it works. Write an appropriately general set of functions that can draw flowers as in Turtle flowers. Write an appropriately general set of functions that can draw shapes as in Turtle pies. The letters of the alphabet can be constructed from a moderate number of basic elements, like vertical and horizontal lines and a few curves.
Design an alphabet that can be drawn with a minimal number of basic elements and then write functions that draw the letters. Read about spirals at https: The main topic of this chapter is the if statement, which executes different code depending on the state of the program.
But first I want to introduce two new operators: For example, suppose the run time of a movie is minutes. You might want to know how long that is in hours.
Conventional division returns a floating-point number:. Floor division returns the integer number of hours, rounding down:. The modulus operator is more useful than it seems. Also, you can extract the right-most digit or digits from a number.
A boolean expression is an expression that is either true or false. Although these operations are probably familiar to you, the Julia symbols are different from the mathematical symbols. There are three logical operators: The semantics meaning of these operators is similar to their meaning in English.
Finally, the! In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:. The boolean expression after if is called the condition. If it is true, the indented statement runs.
If not, nothing happens. Statements like this are called compound statements. There is no limit on the number of statements that can appear in the body. The syntax looks like this:.
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays an appropriate message. If the condition is false, the second set of statements runs. Since the condition must be true or false, exactly one of the alternatives will run.
The alternatives are called branches , because they are branches in the flow of execution. Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:. Again, exactly one branch will run.
There is no limit on the number of elseif statements. Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.
One conditional can also be nested within another. We could have written the example in the previous section like this:.
The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well. Although the non-compulsory indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly.
It is a good idea to avoid them when you can. Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:.
It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do. For example, look at the following function:. If n is 0 or negative, it outputs the word, "Blastoff! A function that calls itself is recursive ; the process of executing it is called recursion.
The rest of the function is similar to countdown: For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to write with a for loop and easy to write with recursion, so it is good to start early.
In Stack Diagrams , we used a stack diagram to represent the state of a program during a function call. The same kind of diagram can help interpret a recursive function. For a recursive function, there might be more than one frame on the stack at the same time. As usual, the top of the stack is the frame for Main. It is empty because we did not create any variables in Main or pass any arguments to it. The four countdown frames have different values for the parameter n.
It does not make a recursive call, so there are no more frames. If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion , and it is generally not a good idea. Here is a minimal program with an infinite recursion:.
In most programming environments, a program with infinite recursion does not really run forever. Julia reports an error message when the maximum recursion depth is reached:. This stacktrace is a little bigger than the one we saw in the previous chapter.
When the error occurs, there are recurse frames on the stack! If you encounter an infinite recursion by accident, review your function to confirm that there is a base case that does not make a recursive call. And if there is a base case, check whether you are guaranteed to reach it. The programs we have written so far accept no input from the user. They just do the same thing every time. Julia provides a built-in function called readline that stops the program and waits for the user to type something.
Before getting input from the user, it is a good idea to print a prompt telling the user what to type:. A semi-colon ; allows to put multiple statements on the same line. In the REPL only the last statement returns its value. If you expect the user to type an integer, you can try to convert the return value to Int When a syntax or runtime error occurs, the error message contains a lot of information, but it can be overwhelming.
The most useful parts are usually:. Syntax errors are usually easy to find, but there are a few gotchas. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line. The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio in decibels.
The formula is. To find the error, it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 3, which uses floor division instead of floating-point division.
One of the operators that compares its operands: One of the operators that combines boolean expressions: A statement that consists of a header and a body. The body is terminated with the keyword end. Eventually, an infinite recursion causes a runtime error. Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch. If you are given three sticks, you may or may not be able to arrange them in a triangle.
For example, if one of the sticks is 12 inches long and the other two are one inch long, you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:. If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle.
Otherwise, you can. Write a function that prompts the user to input three stick lengths, converts them to integers, and uses istriangle to check whether sticks with the given lengths can form a triangle. What is the output of the following program? Draw a stack diagram that shows the state of the program when it prints the result. Write a docstring that explains everything someone would need to know in order to use this function and nothing else.
The following exercises use the ThinkJulia module, described in Case Study: Interface Design:. Read the following function and see if you can figure out what it does see the examples in Case Study: Interface Design.
Then run it and see if you got it right. The Koch curve is a fractal that looks something like A Koch curve. Write a function called koch that takes a turtle and a length as parameters, and that uses the turtle to draw a Koch curve with the given length. Write a function called snowflake that draws three Koch curves to make the outline of a snowflake. The Koch curve can be generalized in several ways.
See https: Many of the Julia functions we have used, such as the math functions, produce return values. In this chapter you will learn to write fruitful functions. Calling the function generates a return value, which we usually assign to a variable or use as part of an expression. The functions we have written so far are void. Speaking casually, they have no return value; more precisely, their return value is nothing.