Riječnik

Odaberite jednu od ključnih riječi s lijeve strane ...

Programming in JuliaBasics

Vrijeme čitanja: ~35 min

Let's begin by developing some basic vocabulary for the elements of a program. This section is an overview: will develop some of these ideas in greater depth in later sections.

Objects

A object is a fundamental entity that may be manipulated by a program. Objects have types; for example, 5 is an Int64 (in other words, an integer which occupies 64 bits) and "Hello world!" is a String. Types are important for the computer to keep track of, since values are stored differently depending on their type. You can check the type of a value using the typeof function: typeof("hello") returns String.

Exercise.
Use the code block below to find the type of 1.0. Does 1.0 have the same type as 1?

# replace this text with code and press enter while holding shift to run

(Note: you probably noticed the Loading or None returned message that appeared briefly when you ran the cell. If that message appears for more than 10 seconds or so, it's likely that the cell has run successfully but doesn't have anything to show as a result. We will discuss this in more detail soon.)

A variable is a name used to refer to a object. We can assign a object (say 41) to a variable (say age) as follows:

age = 41

Variable names must begin with an underscore or letter and contain only letters, digits, underscores, and exclamation points after that. Unicode characters are supported in Julia and can be input by typing appropriate descriptions followed by the tab key (but only in a REPL or notebook, convenient Unicode entry is not supported in this webpage). For example, typing \alpha and then tab will produce α.

Letters in variable names may be uppercase or lowercase, and the case matters. For example extractValues0 is variable name, and data.frame is variable name.

The object assigned to a given variable may be changed as many times as desired with further assignments.

Exercise.
Find the value of x at the end of the following block of code.

x = 3
y = x
x = x + 1
x = y

Solution. The value 3 is assigned to x and then also to y on the second line. After the third line, the value of x is 4, since the right-hand side works out to 4 an is then assigned to the variable x. After the fourth line 3 is of x again, since the value of y is still 3 when the fourth line is executed.

Exercise.
Use the code block below to find out what happens when you try to use a variable that hasn't had any object assigned to it: you get an Error.

num_carrots = 4
num_Carrots

Note that when an error occurs in your code, you get a stack trace which helps you identify the source of the error.

Functions

A function performs a particular task. For example, print(x) writes a string representation of the value of the variable x to the screen.

Prompting a function to perform its task is referred to as calling the function. Functions are called using parentheses following the function's name, and any objects which are needed by the function are supplied between these parentheses, separated by commas. These objects are called arguments.

Some functions, like print are built into the language and are always available. You may also define your own functions using function:

function print_twice(x)
    print(x)
    print(x)
end

print_twice("hey")

function is an example of a keyword: a name with a special meaning in the language. Since it has a special meaning, a keyword may not be used as a variable name.

A function may perform an action, like print_twice, or it may return an object. For example, after the following code block is run, the object 28 will be assigned to the variable y.

function add_one(x)
    return x + 1
end

y = 20 + add_one(7)

In Julia, the return keyword can be omitted if the value to be returned appears at the end of the body of the function. The block above would more commonly be written

function add_one(x)
    x + 1
end

y = 20 + add_one(7)

Alternatively, you can define functions in Julia using standard math notation:

add_one(x) = x + 1

The variable name x in the above block is called a parameter. Parameters play the same role as dummy variables in the definition of a mathematical function (for example, when the squaring function is defined using the notation fx=x2).

An operator is a special kind of function that can be called in a special way. For example, the multiplication operator * can called using the mathematically familiar infix notation 3 * 5, or in the usual way as *(3,5).

Exercise
Arrange the operation descriptions below in order, according the corresponding Julia operator in the list +, ^, *, ÷, //, /. You might need to experiment using the code block below. (Note: the division symbol is \div-[tab].)

division (ordinary real-number division)
rational division (return a fraction object)
integer division (quotient only; no remainder)
addition
multiplication
exponentiation
println(6 + 11)
println(2^5)
println(3 * 4)
println(7÷2)
println(7//2)
println(7/2)

(Note: println is the same as print except that it prints a newline character at the end.)

Statements and expressions

An individual executable unit of code in Julia is called a statement. For example, the assignment age = 41 is a statement. Statements may include expressions, which are combinations of values, variables, operators, and function calls that a language interprets and evaluates to a value. For example, 1 + age + abs(3*-4) is an expression which evaluates to (note that abs is the absolute value function, and we're assuming age is set to the value 41).

Exercise
function f(x) return x^2 end is

2 + 3*f(4) is

y = 13 is

myName = "John" * "Doe" is

an expression
a statement whose execution involves evaluating an expression

Exercises

Exercise
(Try doing this without executing the code.) The expression 1 + 5÷3 + 2^3 evaluates to .

Exercise
(Try doing this without executing the code.) The expression 11/2-11÷2-3 evaluates to , expressed as a decimal.

Exercise
Find the value of x at the end of the following block of code.

x = 3^2
x = x + 1
x = x + 1
y = x÷2
x = y*y
z = 2*x

Exercise
Write a function f which takes a positive integer n as input and returns the $n$th positive odd integer. The last four lines of code check that your function works.

Also, note that you have two boxes: the first is for scratch, and the second is for saving your answer. Once you're happy with your code, copy and paste it into the second box.

function f(n)
    # add code here
end

using Test
@test f(3) == 5
@test f(1) == 1
@test f(100) == 199

Solution. The function in question is n\mapsto 2n-1:

function f(n)
    2n-1
end

using Test
@test f(3) == 5
@test f(1) == 1
@test f(100) == 199

The @ in the name @test has a special meaning in Julia: it indicates that @test is a macro. This means that the code that @test operates on is not evaluated right away. Rather, the code is passed directly to @test to be processed in a manner specified by the definition of the macro @test.

The following example sheds some light on the difference between evaluating code to pass values to a function and passing the code directly to a macro: if x is not defined, then f(x) always throws an error, since the value assigned to x cannot be looked up and passed to the function f. However, @f(x) might not throw an error, because a literal x symbol is what's being passed to the macro @f. As long as @f doesn't try to evaluate x, there might be no problem.

In general, you shouldn't have to worry about macros much. However, you will see macros in use sometimes, and it can be helpful to be aware that what's happening is standard Julia syntax parsing.

Exercise
Select the true statements.

The statement balance = 46.04 assigns the value 46.04 to the variable balance.
The object 33 is a variable.
The value assigned to a variable cannot be changed.
Variable names in Julia are case-sensitive.
Bruno
Bruno Bruno