Try the following example using the Try it option available at the top right corner of the below sample code box

Size: px
Start display at page:

Download "Try the following example using the Try it option available at the top right corner of the below sample code box"

Transcription

1

2 About the Tutorial Elixir is a dynamic, functional language designed for building scalable and maintainable applications. It is built on top of Erlang. Elixir leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain. Audience This tutorial is created for software programmers who aim to learn the fundamentals of Elixir programming language from scratch. This tutorial will give you a basic foundation to start programming in Elixir programming language. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Computer Programming terminologies and exposure to any other programming language. Some familiarity with functional programming will help you in learning Elixir. Execute Elixir Online For most of the examples given in this tutorial, you will find the Try it option. You can make use of this option to execute your Elixir programs on the go and enjoy your learning. Try the following example using the Try it option available at the top right corner of the below sample code box IO.puts "Hello world" Copyright & Disclaimer Copyright 2017 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com i

3 Table of Contents About the Tutorial... i Audience... i Prerequisites... i Execute Elixir Online... i Copyright & Disclaimer... i Table of Contents... ii ELIXIR OVERVIEW... 1 ELIXIR ENVIRONMENT... 2 Installing Elixir... 2 Testing the Setup... 3 ELIXIR BASIC SYNTAX... 4 ELIXIR DATA TYPES... 6 Numerical Types... 6 ELIXIR VARIABLES... 9 Types of Variables... 9 Variable Declaration... 9 Variable Naming Printing Variables ELIXIR OPERATORS Arithmetic Operators Comparison Operators Logical Operators Bitwise Operators Misc Operators ii

4 ELIXIR PATTERN MATCHING ELIXIR DECISION MAKING Elixir If statement Elixir If else statement Elixir Unless statement Elixir - Unless else statement Elixir Cond Statement Elixir Case statement ELIXIR STRINGS Create a String Empty Strings String Interpolation String Concatenation String Length Reversing a String String Comparison String Matching String Functions Binaries Bitstrings ELIXIR CHAR LISTS ELIXIR LISTS AND TUPLES (Linked) Lists Other List functions Tuples Tuples vs. Lists iii

5 ELIXIR KEYWORD LISTS Accessing a Key Inserting a Key Deleting a Key ELIXIR MAPS Creating a Map ELIXIR MODULES Compilation Scripted Mode Module Nesting ELIXIR ALIASES ELIXIR FUNCTIONS Anonymous Functions Named Functions ELIXIR RECURSION ELIXIR LOOPS ELIXIR ENUMERABLES Eager Evaluation ELIXIR STREAMS ELIXIR STRUCTS Defining Structs Accessing and Updating Structs iv

6 ELIXIR PROTOCOLS Defining a Protocol Implementing a Protocol ELIXIR FILE IO The Path Module The File Module ELIXIR PROCESSES The Spawn Function Message Passing Links State ELIXIR SIGILS Regex Strings, Char lists and Word lists Interpolation and Escaping in Sigils Custom Sigils ELIXIR COMPREHENSIONS Basics Filter :into Option ELIXIR TYPESPECS Function Specifications(specs) Custom Types v

7 ELIXIR BEHAVIOURS Defining a Behavior Adopting a Behavior ELIXIR ERROR HANDLING Error Throws Exit After ELIXIR MACROS Quote Unquote Macros ELIXIR LIBRARIES The Binary Module The Crypto Module The Digraph Module The Math Module The Queue Module vi

8 Overview Elixir Elixir is a dynamic, functional language designed for building scalable and maintainable applications. It leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain. Elixir is a functional, dynamic language built on top of Erlang and the Erlang VM. Erlang is a language that was originally written in 1986 by Ericsson to help solve telephony problems like distribution, fault-tolerance, and concurrency. Elixir, written by José Valim, exts Erlang and provides a frilier syntax into the Erlang VM. It does this while keeping the performance of the same level as Erlang. Features of Elixir Let us now discuss a few important features of Elixir: Scalability All Elixir code runs inside lightweight processes that are isolated and exchange information via messages. Fault Tolerance Elixir provides supervisors which describe how to restart parts of your system when things go wrong, going back to a known initial state that is guaranteed to work. This ensures your application/platform is never down. Functional Programming Functional programming promotes a coding style that helps developers write code that is short, fast, and maintainable. Build tools Elixir ships with a set of development tools. Mix is one such tool that makes it easy to create projects, manage tasks, run tests, etc. It also has its own package manager - Hex. Erlang Compatibility Elixir runs on the Erlang VM giving developers complete access to Erlang s ecosystem. 1

9 Environment Elixir In order to run Elixir, you need to set it up locally on your system. To install Elixir, you will first require Erlang. On some platforms, Elixir packages come with Erlang in them. Installing Elixir Let us now understand the installation of Elixir in different Operating Systems. Windows Setup To install Elixir on windows, download installer from and simply click Next to proceed through all steps. You will have it on your local system. If you have any problems while installing it, you can check this page for more info. Mac Setup If you have Homebrew installed, make sure that it is the latest version. For updating, use the following command: brew update Now, install Elixir using the command given below: brew install elixir Ubuntu/Debian Setup The steps to install Elixir in an Ubuntu/Debian setup is as follows: Add Erlang Solutions repo: wget && sudo dpkg -i erlang-solutions_1.0_all.deb sudo apt-get update Install the Erlang/OTP platform and all of its applications: sudo apt-get install esl-erlang Install Elixir: sudo apt-get install elixir 2

10 Other Linux Distros If you have any other Linux distribution, please visit this page to set up elixir on your local system. Testing the Setup To test the Elixir setup on your system, open your terminal and enter iex in it. It will open the interactive elixir shell like the following: Erlang/OTP 19 [erts-8.0] [source-6dc93c1] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> Elixir is now successfully set up on your system. 3

11 Basic Syntax Elixir We will start with the customary 'Hello World' program. To start the Elixir interactive shell, enter the following command. iex After the shell starts, use the IO.puts function to "put" the string on the console output. Enter the following in your Elixir shell: IO.puts "Hello world" In this tutorial, we will use the Elixir script mode where we will keep the Elixir code in a file with the extension.ex. Let us now keep the above code in the test.ex file. In the succeeding step, we will execute it using elixirc: IO.puts "Hello world" Let us now try to run the above program as follows: $elixirc test.ex The above program generates the following result: Hello World Here we are calling a function IO.puts to generate a string to our console as output. This function can also be called the way we do in C, C++, Java, etc., providing arguments in parentheses following the function name: IO.puts("Hello world") Comments Single line comments start with a '#' symbol. There's no multi-line comment, but you can stack multiple comments. For example: #This is a comment in Elixir Line Endings There are no required line ings like ';' in Elixir. However, we can have multiple statements in the same line, using ';'. For example, IO.puts("Hello"); IO.puts("World!") 4

12 The above program generates the following result: Hello World Identifiers Identifiers like variables, function names are used to identify a variable, function, etc. In Elixir, you can name your identifiers starting with a lower case alphabet with numbers, underscores and upper case letters thereafter. This naming convention is commonly known as snake_case. For example, following are some valid identifiers in Elixir: var1 variable_2 one_m0r3_variable Please note that variables can also be named with a leading underscore. A value that is not meant to be used must be assigned to _ or to a variable starting with underscore: _some_random_value = 42 Also elixir relies on underscores to make functions private to modules. If you name a function with a leading underscore in a module, and import that module, this function will not be imported. There are many more intricacies related to function naming in Elixir which we will discuss in coming chapters. Reserved Words Following words are reserved and cannot be used as variables, module or function names. after and catch do inbits inlist nil else not or false fn in rescue true when xor MODULE FILE DIR ENV CALLER 5

13 Data Types Elixir For using any language, you need to understand the basic data types the language supports. In this chapter, we will discuss 7 basic data types supported by the elixir language: integers, floats, Booleans, atoms, strings, lists and tuples. Numerical Types Elixir, like any other programming language, supports both integers and floats. If you open your elixir shell and input any integer or float as input, it'll return its value. For example, 42 When the above program is run, it produces the following result: 42 You can also define numbers in octal, hex and binary bases. OCTAL To define a number in octal base, prefix it with '0o'. For example, 0o52 in octal is equivalent to 42 in decimal. HEXADECIMAL To define a number in decimal base, prefix it with '0x'. For example, 0xF1 in hex is equivalent to 241 in decimal. BINARY To define a number in binary base, prefix it with '0b'. For example, 0b1101 in binary is equivalent to 13 in decimal. Elixir supports 64bit double precision for floating point numbers. And they can also be defined using an exponentiation style. For example, can be written as e10 Atoms Atoms are constants whose name is their value. They can be created using the color(:) symbol. For example, :hello Booleans Elixir supports true and false as Booleans. Both these values are in fact attached to atoms :true and :false respectively. 6

14 Strings Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. They can span multiple lines and contain interpolations. To define a string simply enter it in double quotes: "Hello world" To define multiline strings, we use a syntax similar to python with triple double quotes: """ Hello World! """ We'll learn about strings, binaries and char lists (similar to strings) in depth in the strings chapter. Binaries Binaries are sequences of bytes enclosed in << >> separated with a comma. For example, << 65, 68, 75>> Binaries are mostly used to handle bits and bytes related data, if you have any. They can, by default, store 0 to 255 in each value. This size limit can be increased by using the size function that says how many bits it should take to store that value. For example, <<65, 255, 289::size(15)>> Lists Elixir uses square brackets to specify a list of values. Values can be of any type. For example, [1, "Hello", :an_atom, true] Lists come with inbuilt functions for head and tail of the list named hd and tl which return the head and tail of the list respectively. Sometimes when you create a list, it'll return a char list. This is because when elixir sees a list of printable ASCII characters, it prints it as a char list. Please note that strings and char lists are not equal. We'll discuss lists further in later chapters. Tuples Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value. { 1, "Hello", :an_atom, true } 7

15 A question arises here why provide both lists and tuples when they both work in the same way? Well, they have different implementations. Lists are actually stored as linked lists, so insertions, deletions are very fast in lists. Tuples, on the other hand, are stored in contiguous memory block, which make accessing them faster but adds an additional cost on insertions and deletions. 8

16 Variables Elixir A variable provides us with named storage that our programs can manipulate. Each variable in Elixir has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. Types of Variables Elixir supports the following basic types of variables: Integer These are used for Integers. They are of size 32bit on a 32bit architecture and 64 bits on a 64-bit architecture. Integers are always signed in elixir. If an integer starts to expand in size above its limit, elixir convers it in a Big Integer which takes up memory in range 3 to n words whichever can fit it in memory. Floats Floats have a 64-bit precision in elixir. They are also like integers in terms of memory. When defining a float, exponential notation can be used. Boolean They can take up 2 values which is either true or false. Strings Strings are utf-8 encoded in elixir. They have a strings module which provides a lot of functionality to the programmer to manipulate strings. Anonymous Functions/Lambdas These are functions that can be defined and assigned to a variable, which can then be used to call this function. Collections There are a lot of collection types available in Elixir. Some of them are Lists, Tuples, Maps, Binaries, etc. These will be discussed in subsequent chapters. Variable Declaration A variable declaration tells the interpreter where and how much to create the storage for the variable. Elixir does not allow us to just declare a variable. A variable must be declared and assigned a value at the same time. For example, to create a variable named life and assign it a value 42, we do the following: 9

17 life = 42 This will bind the variable life to value 42. If we want to reassign this variable a new value, we can do this by using the same syntax as above, i.e., life = "Hello world" Variable Naming Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the by an optional '?' OR '!'. Variable names can also be started with a leading underscore but that must be used only when ignoring the variable, i.e., that variable will not be used again but is needed to be assigned to something. Printing Variables In the interactive shell, variables will print if you just enter the variable name. For example, if you create a variable: life = 42 And enter 'life' in your shell, you'll get the output as: 42 But if you want to output a variable to the console (When running an external script from a file), you need to provide the variable as input to IO.puts function: or life = 42 IO.puts life life = 42 IO.puts(life) This will give you the following output: 42 10

18 Operators Elixir An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are a LOT of operators provided by elixir. They are divided in the following categories: Arithmetic operators Comparison operators Boolean operators Misc operators Arithmetic Operators The following table shows all the arithmetic operators supported by Elixir language. Assume variable A holds 10 and variable B holds 20, then: Operator Description Example + Adds 2 numbers. A + B will give 30 - Subtracts second number from first. A-B will give -10 * Multiplies two numbers. A*B will give 200 / Divides first number from second. This casts the numbers in floats and gives a float result. A/B will give 0.5 div This function is used to get the quotient on division. div(10,20) will give 0 rem This function is used to get the remainder on division. rem(a, B) will give 10 Example Try the following code to understand all arithmetic operators in Elixir. a = 10 b = 20 #Addition IO.puts("Addition " <> to_string(a+b)) 11

19 #Subtraction IO.puts("Subtraction " <> to_string(a-b)) #Multiplication IO.puts("Multiplication " <> to_string(a*b)) #Division IO.puts("Division " <> to_string(a/b)) #Integer division IO.puts("Integer division " <> to_string(div(a,b))) #Modulo IO.puts("Modulo " <> to_string(rem(a,b))) The above program generates the following result. Addition 30 Subtraction -10 Multiplication 200 Division 0.5 Integer division 0 Modulo 10 Comparison Operators The comparison operators in Elixir are mostly common to those provided in most other languages. The following table sums up comparison operators in Elixir. Assume variable A holds 10 and variable B holds 20, then: Operator Description Example == Checks if value on left is equal to value on right(type casts values if they are not the same type). A == B will give false!= Checks if value on left is not equal to value on right. A!= B will give true 12

20 === Checks if type of value on left equals type of value on right, if yes then check the same for value. A === B will give false!== Same as above but checks for inequality instead of equality. A!== B will give true > Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. A > B will give false < Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. A < B will give true >= Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. A >= B will give false <= Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. A <= B will give true Example Try the following code to understand all arithmetic operators in Elixir. a = 10 b = 20 IO.puts("a == b " <> to_string(a == b)) IO.puts("a!= b " <> to_string(a!= b)) IO.puts("a === b " <> to_string(a === b)) IO.puts("a!== b" <> to_string(a!== b)) IO.puts("a > b " <> to_string(a > b)) IO.puts("a < b " <> to_string(a < b)) IO.puts("a >= b " <> to_string(a >= b)) IO.puts("a <= b " <> to_string(a <= b)) 13

21 The above program generates the following result. a == b false a!= b true a === b false a!== b true a > b false a < b true a >= b false a <= b true Logical Operators Elixir provides 6 logical operators: and, or, not, &&, and!. The first three, and or not are strict Boolean operators, which means that they expect their first argument to be a Boolean. Non-Boolean argument will raise an error. While the next three, &&, and! are non-strict; these do not require us to have the first value strictly as a Boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then: Operator Description Example and Checks if both values provided are truthy, if yes, then returns the value of second variable. (Logical and) A and B will give 20 or Checks if either value provided is truthy. Returns whichever value is truthy. Else returns false. (Logical or) A or B will give true not Unary operator which inverts the value of given input. not A will give false && Non-strict and. Works same as and but does not expect first argument to be a Boolean. B && A will give 20 Non-strict or. Works same as or but does not expect first argument to be a Boolean. B A will give true! Non-strict not. Works same as not but does not expect the argument to be a Boolean.!A will give false NOTE: and, or, && and are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example, 14

22 false and raise("an error") #This won't raise an error as raise function wont get executed because of short circuiting nature of and operator. Example Try the following code to understand all arithmetic operators in Elixir. a = true b = 20 IO.puts("a and b " <> to_string(a and b)) IO.puts("a or b " <> to_string(a or b)) IO.puts("not a " <> to_string(not a)) IO.puts("b && a" <> to_string(b && a)) IO.puts("b a " <> to_string(b a)) IO.puts("!a " <> to_string(!a)) The above program generates the following result: a and b 20 a or b true not a false b && a true b a 20!a false Bitwise Operators Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following command in your shell: use Bitwise 15

23 Operator Description Example &&& Bitwise and operator copies a bit to result if it exists in both operands. A &&& B will give 4 Bitwise or operator copies a bit to result if it exists in either operand. A B will give 7 >>> Bitwise right shift operator shifts first operand bits to the right by the number specified in second operand. A >>> B will give 0 <<< Bitwise left shift operator shifts first operand bits to the left by the number specified in second operand. A <<< B will give 320 ^^^ Bitwise XOR operator copies a bit to result only if it is different on both operands. A ^^^ B will give 3 ~~~ Unary bitwise does not invert the bits on the given number. ~~~A will give -6 Assume A to be 5 and B to be 6 for the following examples. Example Try the following code to understand all arithmetic operators in Elixir. a = 5 b = 6 use Bitwise IO.puts("a &&& b " <> to_string(a &&& b)) IO.puts("a b " <> to_string(a b)) IO.puts("a >>> b " <> to_string(a >>> b)) IO.puts("a <<< b" <> to_string(a <<< b)) IO.puts("a ^^^ b " <> to_string(a ^^^ b)) IO.puts("~~~a " <> to_string(~~~a)) 16

24 The above program generates the following result. a &&& b 4 a b 7 a >>> b 0 a <<< b 320 a ^^^ b 3 ~~~a -6 Misc Operators Other than the above operators, Elixir also provides a range of other operators that make it quite a powerful language. Concatenation Operator Elixir provides a string concatenation operator, '<>'. This is used to concatenate 2 strings. For example, IO.puts("Hello"<>" "<>"world") The above command generates the following result. Hello World Match The match operator, '=' makes use of the pattern matching feature of the language. We will discuss this operator in detail in a subsequent chapter on Pattern Matching. Please note that = is not only an assignment operator. When we have the left value as a variable and right value as a literal or another variable, value from right is bound to the variable, i.e., assignment takes place. But if we have a variable on the right and literal on left, pattern matching happens. The same is the case when both values are literals. Pin The pin operator, '^' is a unary operator used by prefixing a variable name. It makes sure that the variable when used with the match operator is not assigned a value, but is matched to that value. For example, a = 12 #assignment a = 13 #assignment ^a = 13 #Pattern matching 17

25 Pipe The pipe operator, ' >' works like the pipe operator in Unix shells. It allows us to pipe the output from one function to the other. For example, if we need to pipe the result of addition in IO.puts, we will use: (4+3) > IO.puts This will recognize that we have piped the result of addition in the IO.puts function. This will print 7 on your console. String Match The string match operator, '=~', takes a string on the left and either a string or a regular expression on the right. If the string on the right is a substring of left, true is returned. If the regular expression on the right matches the string on the left, true is returned. Otherwise false is returned. For example, "tutorialspoint" =~ "poi" #True "tutorialspoint" =~ ~r/[a-z]*/ #True "tutorialspoint" =~ ~r/[0-9]*/ #False Note that regexes start with a '~r' prefix in Elixir. Code Point It is a unary operator, '?' which returns the UTF-8 code point of the character immediately to its right. It can take only one character and accepts Escape Sequences. For example,?a #returns 97?\s #returns 32 Capture The capture operator, '&' is used when defining anonymous functions. We will discuss this in detail in the functions chapter. Ternary Elixir does not have a ternary operator. We can achieve same functionality using the if else statement: a = if true, do: "True!", else: "False!" 18

26 In This operator checks if left item exists in the enumerable structure on the right. For example, we can check for an atom in a list, tuple, etc. of atoms using this operator: :yes in [:true, :false, :yes] The above statement returns true as :yes exists in the list. 19

27 Pattern Matching Elixir Pattern matching is a technique which Elixir inherits form Erlang. It is a very powerful technique that allows us to extract simpler substructures from complicated data structures like lists, tuples, maps, etc. A match has 2 main parts, a left and a right side. The right side is a data structure of any kind. The left side attempts to match the data structure on the right side and bind any variables on the left to the respective substructure on the right. If a match is not found, the operator raises an error. The simplest match is a lone variable on the left and any data structure on the right. This variable will match anything. For example, x = 12 x = "Hello" IO.puts(x) You can place variables inside a structure so that you can capture a substructure. For example, [var_1, _unused_var, var_2] = [{"First variable"}, 25, "Second variable" ] IO.puts(var_1) IO.puts(var_2) This will store the values, {"First variable"} in var_1 and "Second variable" in var_2. There is also a special _ variable(or variables prefixed with '_') that works exactly like other variables but tells elixir, "Make sure something is here, but I don't care exactly what it is.". In the previous example, _unused_var was one such variable. We can match more complicated patterns using this technique. For example, if you want to unwrap and get a number in a tuple which is inside a list which itself is in a list, you can use the following command: [_, [_, {a}]] = ["Random string", [:an_atom, {24}]] IO.puts(a) This will bind a to 24. Other values are ignored as we are using '_'. In pattern matching, if we use a variable on the right, its value is used. If you want to use the value of a variable on the left, you'll need to use the pin operator. 20

28 For example, if you have a variable "a" having value 25 and you want to match it with another variable "b" having the same value 25, then you need to enter: a = 25 b = 25 ^a = b The last line matches the current value of a, instead of assigning it, to the value of b. If we have a non-matching set of left and right hand side, the match operator raises an error. For example, if we try to match a tuple with a list or a list of size 2 with a list of size 3, an error will be displayed. 21

29 Decision Making Elixir Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general from of a typical decision making structure found in most of the programming language: Elixir provides if/else conditional constructs like many other programming languages. It also has a cond statement which calls the first true value it finds. Case is another control flow statement which uses pattern matching to control the flow of the program. Let's have a deep look at them. Elixir provides the following types of decision making statements. Click the following links to check their detail. 22

30 S.No. Statement and Description if statement 1 An if statement consists of a Boolean expression followed by do, one or more executable statements and finally an keyword. Code in if statement executes only if Boolean condition evaluates to true. 2 if..else statement An if statement can be followed by an optional else statement (within the do.. block), which executes when the Boolean expression is false. 3 unless statement An unless statement has the same body as an if statement. The code within the unless statement executes only when the condition specified is false. unless..else statement 4 An unless..else statement has the same body as an if..else statement. The code within the unless statement executes only when the condition specified is false. cond 5 A cond statement is used where we want to execute code on basis of several conditions. It kind of works like an if...else if.else construct in several other programming languages. case 6 Case statement can be considered as a replacement for switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, eelixir executes code associated with that case and exits case statement. 23

31 Elixir If statement An if statement consists of a Boolean expression followed by one or more statements. Syntax The syntax of an if statement is as follows: if boolean-statement do #Code to be executed if condition is satisfied If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the keyword of the given if statement will be executed. Flow Diagram Example a = true if a === true do IO.puts "Variable a is true!" IO.puts "So this code block is executed" IO.puts "Outside the if statement" 24

32 The above program will generate the following result. Variable a is true! So this code block is executed Outside the if statement Elixir If else statement An if..else statement consists of a Boolean expression followed by one or more statements. This is further followed by an else statement with one or more statements. Syntax The syntax of an if..else statement is as follows: if boolean-statement do else #Code to be executed if condition is satisfied #Code to be executed if condition is not satisfied If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to false, then the code after the else keyword of the given if statement will be executed. Flow Diagram 25

33 Example a = false if a === true do IO.puts "Variable a is true!" else IO.puts "Variable a is false!" IO.puts "Outside the if statement" The above program will generate the following result. Variable a is false! Outside the if statement Elixir Unless statement An unless statement consists of a Boolean expression followed by one or more statements. Syntax The syntax of an unless statement is as follows: unless boolean-statement do #Code to be executed if condition is false If the Boolean expression evaluates to false, then the block of code inside the unless statement will be executed. If the Boolean expression evaluates to true, then the first set of code after the keyword of the given unless statement will be executed. Example a = false unless a === true do IO.puts "Condition is not satisfied" IO.puts "So this code block is executed" IO.puts "Outside the unless statement" 26

34 The above program generates the following result. Condition is not satisfied So this code block is executed Outside the unless statement Elixir - Unless else statement An unless..else statement consists of a Boolean expression followed by one or more statements. This is further followed by an else statement with its own block of statements. Syntax The syntax of an unless..else statement is as follows: unless boolean-statement do else #Code to be executed if condition is false #Code to be executed if condition is true If the Boolean expression evaluates to false, then the block of code inside the unless statement will be executed. If the Boolean expression evaluates to true, then the code after the else keyword of the given unless statement will be executed. Example a = false unless a === false do else IO.puts "Condition is not satisfied" IO.puts "Condition was satisfied!" IO.puts "Outside the unless statement" The above program generates the following result. Condition was satisfied! Outside the unless statement 27

35 Elixir Cond Statement Cond statements are used where we want to execute a code on the basis of several conditions. It works like an if.else construct in several other programming languages. Syntax The syntax of a cond statement is as follows: cond do else boolean_expression_1 -> #Execute if this condition is true boolean_expression_2 -> #Execute if this condition is true... true -> #Execute if none of the above conditions are true If any of the boolean_expression Boolean expressions evaluates to true, then the block of code inside the statement will be executed. The way cond statement works is - it will start from the first condition and check if it is true. If true, it will execute the code corresponding to that condition, otherwise, it will move on to the next condition. It will repeat this till a condition matches. If no condition matches, it raises a CondClauseError, i.e., the condition clause was not satisfied. To prevent this, a true statement should always be used at the of a cond statement. Example guess = 46 cond do guess == 10 -> IO.puts "You guessed 10!" guess == 46 -> IO.puts "You guessed 46!" guess == 42 -> IO.puts "You guessed 42!" true -> IO.puts "I give up." The above program generates the following result: You guessed 46! Elixir Case statement Case statement can be considered as a replacement for the switch statement in imperative languages. Case takes a variable/literal and applies pattern matching to it with different cases. If any case matches, Elixir executes the code associated with that case and exits the case statement. If no match is found, it exits the statement with an CaseClauseError that displays no matching clauses were found. You should always 28

36 have a case with _ which matches all values. This helps in prevention of the abovementioned error. Also this is comparable to the default case in switch-case statements. Syntax The syntax of an if statement is as follows: case value do matcher_1 -> #code to execute if value matches matcher_1 matcher_1 -> #code to execute if value matches matcher_2 matcher_1 -> #code to execute if value matches matcher_3... _ -> #code to execute if value does not match any of the above Example case 3 do 1 -> IO.puts("Hi, I'm one") 2 -> IO.puts("Hi, I'm two") 3 -> IO.puts("Hi, I'm three") _ -> IO.puts("Oops, you dont match!") The above program generates the following result. Hi, I'm three Note that the case selection is done using pattern matching, so you can use the standard pattern matching techniques. 29

37 Strings Elixir Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. Unlike C and C++ where the default strings are ASCII encoded and only 256 different characters are possible, UTF-8 consists of code points. This means that UTF-8 encoding consists of those many different possible characters. Since the strings use utf-8, we can also use symbols like: ö, ł, etc. Create a String To create a string variable, simply assign a string to a variable: str = "Hello world" To print this to your console, simply call the IO.puts function and pass it the variable str: str = "Hello world" IO.puts(str) The above program generates the following result. Hello World Empty Strings You can create an empty string using the string literal, "". For example, a = "" if String.length(a) === 0 do IO.puts("a is an empty string") The above program generates the following result. a is an empty string String Interpolation String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Elixir supports string interpolation, to use a variable in a string, when writing it, wrap it with curly braces and prep the curly braces with a '#' sign. 30

38 For example, x = "Apocalypse" y = "X-men #{x}" IO.puts(y) This will take the value of x and substitute it in y. The above code will generate the following result: X-men Apocalypse String Concatenation We have already seen the use of String concatenation in previous chapters. The '<>' operator is used to concatenate strings in Elixir. To concatenate 2 strings, x = "Dark" y = "Knight" z = x <> " " <> y IO.puts(z) The above code generates the following result: Dark Knight String Length To get the length of the string, we use the String.length function. Pass the string as a parameter and it will show you its size. For example, IO.puts(String.length("Hello")) The above program generates the following result: 5 Reversing a String To reverse a string, pass it to the String.reverse function. For example, IO.puts(String.reverse("Elixir")) The above program generates the following result: rixile 31

39 String Comparison To compare 2 strings, we can use the == or the === operators. For example, var_1 = "Hello world" var_2 = "Hello Elixir" if var_1 === var_2 do IO.puts("#{var_1} and #{var_2} are the same") else IO.puts("#{var_1} and #{var_2} are not the same") The above program generates the following result: Hello world and Hello elixir are not the same. String Matching We have already seen the use of the =~ string match operator. To check if a string matches a regex, we can also use the string match operator or the String.match? function. For example, IO.puts(String.match?("foo", ~r/foo/)) IO.puts(String.match?("bar", ~r/foo/)) The above program generates the following result: true false This same can also be achieved by using the =~ operator. For example, IO.puts("foo" =~ ~r/foo/) The above program generates the following result: true 32

40 String Functions Elixir supports a large number of functions related to strings, some of the most used are listed in the following table. S.No. Function and its Purpose 1 at(string, position) Returns the grapheme at the position of the given utf8 string. If position is greater than string length, then it returns nil. 2 capitalize(string) Converts the first character in the given string to uppercase and the remainder to lowercase. 3 contains?(string, contents) Checks if string contains any of the given contents. 4 downcase(string) Converts all characters in the given string to lowercase. 5 s_with?(string, suffixes) Returns true if string s with any of the suffixes given. 6 first(string) Returns the first grapheme from a utf8 string, nil if the string is empty. 7 last(string) Returns the last grapheme from a utf8 string, nil if the string is empty. 8 replace(subject, pattern, replacement, options \\ []) Returns a new string created by replacing occurrences of pattern in subject with replacement. slice(string, start, len) 9 Returns a substring starting at the offset start, and of length len. 33

41 split(string) 10 Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored. Groups of whitespace are treated as a single occurrence. Divisions do not occur on non-breaking whitespace 11 upcase(string) Converts all characters in the given string to uppercase Binaries A binary is just a sequence of bytes. Binaries are defined using << >>. For example: << 0, 1, 2, 3 >> Of course, those bytes can be organized in any way, even in a sequence that does not make them a valid string. For example, << 239, 191, 191 >> Strings are also binaries. And the string concatenation operator <> is actually a Binary concatenation operator: IO.puts(<< 0, 1 >> <> << 2, 3 >>) The above code generates the following result: << 0, 1, 2, 3 >> Note the ł character. Since this is utf-8 encoded, this character representation takes up 2 bytes. Since each number represented in a binary is meant to be a byte, when this value goes up from 255, it is truncated. To prevent this, we use size modifier to specify how many bits we want that number to take. For example: IO.puts(<< 256 >>) # truncated, it'll print << 0 >> IO.puts(<< 256 :: size(16) >>) #Takes 16 bits/2 bytes, will print << 1, 0 >> The above program will generate the following result: << 0 >> << 1, 0 >> 34

42 We can also use the utf8 modifier, if a character is code point then, it will be produced in the output; else the bytes: IO.puts(<< 256 :: utf8 >>) The above program generates the following result: Ā We also have a function called is_binary that checks if a given variable is a binary. Note that only variables which are stored as multiples of 8bits are binaries. Bitstrings If we define a binary using the size modifier and pass it a value that is not a multiple of 8, we up with a bitstring instead of a binary. For example, bs = << 1 :: size(1) >> IO.puts(bs) IO.puts(is_binary(bs)) IO.puts(is_bitstring(bs)) The above program generates the following result: << 1::size(1) >> false true This means that variable bs is not a binary but rather a bitstring. We can also say that a binary is a bitstring where the number of bits is divisible by 8. Pattern matching works on binaries as well as bitstrings in the same way. 35

43 Char lists Elixir A char list is nothing more than a list of characters. Consider the following program to understand the same. IO.puts('Hello') IO.puts(is_list('Hello')) The above program generates the following result: Hello true Instead of containing bytes, a char list contains the code points of the characters between single-quotes. So while the double-quotes represent a string (i.e. a binary), singlequotes represent a char list (i.e. a list). Note that IEx will generate only code points as output if any of the chars is outside the ASCII range. Char lists are used mostly when interfacing with Erlang, in particular old libraries that do not accept binaries as arguments. You can convert a char list to a string and back by using the to_string(char_list) and to_char_list(string) functions: IO.puts(is_list(to_char_list("hełło"))) IO.puts(is_binary(to_string ('hełło'))) The above program generates the following result: true true NOTE: The functions to_string and to_char_list are polymorphic, i.e., they can take multiple types of input like atoms, integers and convert them to strings and char lists respectively. 36

44 Lists and Tuples Elixir (Linked) Lists A linked list is a heterogeneous list of elements that are stored at different locations in memory and are kept track of by using references. Linked lists are data structures especially used in functional programming. Elixir uses square brackets to specify a list of values. Values can be of any type: [1, 2, true, 3] When Elixir sees a list of printable ASCII numbers, Elixir will print that as a char list (literally a list of characters). Whenever you see a value in IEx and you are not sure what it is, you can use the i function to retrieve information about it. IO.puts([104, 101, 108, 108, 111]) The above characters in the list are all printable. When the above program is run, it produces the following result: 'hello' You can also define lists the other way round, using single quotes: IO.puts(is_list('Hello')) When the above program is run, it produces the following result: true Keep in mind single-quoted and double-quoted representations are not equivalent in Elixir as they are represented by different types Length of a List To find the length of a list, we use the length function as in the following program: IO.puts(length([1, 2, :true, "str"])) The above program generates the following result: 4 Concatenation and Subtraction Two lists can be concatenated and subtracted using the ++ and -- operators. Consider the following example to understand the functions. 37

45 IO.puts([1, 2, 3] ++ [4, 5, 6]) IO.puts([1, true, 2, false, 3, true] -- [true, false]) This will give you a concatenated string in the first case and a subtracted string in the second. The above program generates the following result: [1, 2, 3, 4, 5, 6] [1, 2, 3, true] Head and Tail of a List The head is the first element of a list and the tail is the remainder of a list. They can be retrieved with the functions hd and tl. Let us assign a list to a variable and retrieve its head and tail. list = [1, 2, 3] IO.puts(hd(list)) IO.puts(tl(list)) This will give us the head and tail of the list as output. The above program generates the following result: 1 [2, 3] Note: Getting the head or the tail of an empty list is an error. Other List functions Elixir standard library provides a whole lot of functions to deal with lists. We will have a look at some of those here. You can check out the rest here - List. S.No. Function Name and Description delete(list, item) 1 Deletes the given item from the list. Returns a list without the item. If the item occurs more than once in the list, just the first occurrence is removed. delete_at(list, index) 2 Produces a new list by removing the value at the specified index. Negative indices indicate an offset from the of the list. If index is out of bounds, the original list is returned. 38

46 3 first(list) Returns the first element in list or nil if list is empty. 4 flatten(list) Flattens the given list of nested lists. insert_at(list, index, value) 5 Returns a list with value inserted at the specified index. Note that index is capped at the list length. Negative indices indicate an offset from the of the list. 6 last(list) Returns the last element in list or nil if list is empty. Tuples Tuples are also data structures which store a number of other structures within them. Unlike lists, they store elements in a contiguous block of memory. This means accessing a tuple element per index or getting the tuple size is a fast operation. Indexes start from zero. Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value: {:ok, "hello"} Length of a Tuple To get the length of a tuple, use the tuple_size function as in the following program: IO.puts(tuple_size({:ok, "hello"})) The above program generates the following result: 2 Apping a Value To app a value to the tuple, use the Tuple.app function: tuple = {:ok, "Hello"} Tuple.app(tuple, :world) This will create and return a new tuple: {:ok, "Hello", :world} 39

47 Insertng a Value To insert a value at a given position, we can either use the Tuple.insert_at function or the put_elem function. Consider the following example to understand the same: tuple = {:bar, :baz} new_tuple_1 = Tuple.insert_at(tuple, 0, :foo) new_tuple_2 = put_elem(tuple, 1, :foobar) Notice that put_elem and insert_at returned new tuples. The original tuple stored in the tuple variable was not modified because Elixir data types are immutable. By being immutable, Elixir code is easier to reason about as you never need to worry if a particular code is mutating your data structure in place. Tuples vs. Lists What is the difference between lists and tuples? Lists are stored in memory as linked lists, meaning that each element in a list holds its value and points to the following element until the of the list is reached. We call each pair of value and pointer a cons cell. This means accessing the length of a list is a linear operation: we need to traverse the whole list in order to figure out its size. Updating a list is fast as long as we are preping elements. Tuples, on the other hand, are stored contiguously in memory. This means getting the tuple size or accessing an element by index is fast. However, updating or adding elements to tuples is expensive because it requires copying the whole tuple in memory. 40

48 Keyword lists Elixir So far, we have not discussed any associative data structures, i.e., data structures that can associate a certain value (or multiple values) to a key. Different languages call these features with different names like dictionaries, hashes, associative arrays, etc. In Elixir, we have two main associative data structures: keyword lists and maps. In this chapter, we will focus on Keyword lists. In many functional programming languages, it is common to use a list of 2-item tuples as the representation of an associative data structure. In Elixir, when we have a list of tuples and the first item of the tuple (i.e. the key) is an atom, we call it a keyword list. Consider the following example to understand the same: list = [{:a, 1}, {:b, 2}] Elixir supports a special syntax for defining such lists. We can place the colon at the of each atom and get rid of the tuples entirely. For example, list_1 = [{:a, 1}, {:b, 2}] list_2 = [a: 1, b: 2] IO.puts(list_1 == list_2) The above program will generate the following result: true Both of these represent a keyword list. Since keyword lists are also lists, we can use all the operations we used on lists on them. To retrieve the value associated with an atom in the keyword list, pass the atom as to [] after the name of the list: list = [a: 1, b: 2] IO.puts(list[:a]) The above program generates the following result: 1 Keyword lists have three special characteristics: Keys must be atoms. Keys are ordered, as specified by the developer. Keys can be given more than once. In order to manipulate keyword lists, Elixir provides the Keyword module. Remember, though, keyword lists are simply lists, and as such they provide the same linear performance characteristics as lists. The longer the list, the longer it will take to find a 41

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Haskell Programming About the Tutorial Haskell is a widely used purely functional language. Functional programming is based on mathematical functions. Besides Haskell, some of the other popular languages that follow Functional

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design i About the Tutorial A compiler translates the codes written in one language to some other language without changing the meaning of the program. It is also expected that a compiler should make the target

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

Language Reference Manual

Language Reference Manual ALACS Language Reference Manual Manager: Gabriel Lopez (gal2129) Language Guru: Gabriel Kramer-Garcia (glk2110) System Architect: Candace Johnson (crj2121) Tester: Terence Jacobs (tj2316) Table of Contents

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

This tutorial is designed for all those software professionals who are keen on learning the basics of Clojure and how to put it into practice.

This tutorial is designed for all those software professionals who are keen on learning the basics of Clojure and how to put it into practice. About the Tutorial Clojure is a high level, dynamic functional programming language. It is designed, based on the LISP programming language, and has compilers that makes it possible to be run on both Java

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Typescript on LLVM Language Reference Manual

Typescript on LLVM Language Reference Manual Typescript on LLVM Language Reference Manual Ratheet Pandya UNI: rp2707 COMS 4115 H01 (CVN) 1. Introduction 2. Lexical Conventions 2.1 Tokens 2.2 Comments 2.3 Identifiers 2.4 Reserved Keywords 2.5 String

More information

Chapter 2 Working with Data Types and Operators

Chapter 2 Working with Data Types and Operators JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics

More information

This is an introductory tutorial, which covers the basics of Jython and explains how to handle its various modules and sub-modules.

This is an introductory tutorial, which covers the basics of Jython and explains how to handle its various modules and sub-modules. About the Tutorial Jython is the JVM implementation of the Python programming language. It is designed to run on the Java platform. Jython was created in 1997 by Jim Hugunin. It closely follows the standard

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Chapter 17. Fundamental Concepts Expressed in JavaScript

Chapter 17. Fundamental Concepts Expressed in JavaScript Chapter 17 Fundamental Concepts Expressed in JavaScript Learning Objectives Tell the difference between name, value, and variable List three basic data types and the rules for specifying them in a program

More information

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure C Overview Basic C Program Structure C OVERVIEW BASIC C PROGRAM STRUCTURE Goals The function main( )is found in every C program and is where every C program begins speed execution portability C uses braces

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Client-Side Web Technologies. JavaScript Part I

Client-Side Web Technologies. JavaScript Part I Client-Side Web Technologies JavaScript Part I JavaScript First appeared in 1996 in Netscape Navigator Main purpose was to handle input validation that was currently being done server-side Now a powerful

More information

Full file at C How to Program, 6/e Multiple Choice Test Bank

Full file at   C How to Program, 6/e Multiple Choice Test Bank 2.1 Introduction 2.2 A Simple Program: Printing a Line of Text 2.1 Lines beginning with let the computer know that the rest of the line is a comment. (a) /* (b) ** (c) REM (d)

More information

JME Language Reference Manual

JME Language Reference Manual JME Language Reference Manual 1 Introduction JME (pronounced jay+me) is a lightweight language that allows programmers to easily perform statistic computations on tabular data as part of data analysis.

More information

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C Overview The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments

More information

You must have a basic understanding of GNU/Linux operating system and shell scripting.

You must have a basic understanding of GNU/Linux operating system and shell scripting. i About the Tutorial This tutorial takes you through AWK, one of the most prominent text-processing utility on GNU/Linux. It is very powerful and uses simple programming language. It can solve complex

More information

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science) The C Programming Language (with material from Dr. Bin Ren, William & Mary Computer Science) 1 Overview Motivation Hello, world! Basic Data Types Variables Arithmetic Operators Relational Operators Assignments

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

SECTION II: LANGUAGE BASICS

SECTION II: LANGUAGE BASICS Chapter 5 SECTION II: LANGUAGE BASICS Operators Chapter 04: Basic Fundamentals demonstrated declaring and initializing variables. This chapter depicts how to do something with them, using operators. Operators

More information

Scheme as implemented by Racket

Scheme as implemented by Racket Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed C Overview C OVERVIEW Goals speed portability allow access to features of the architecture speed C fast executables allows high-level structure without losing access to machine features many popular languages

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Maciej Sobieraj. Lecture 1

Maciej Sobieraj. Lecture 1 Maciej Sobieraj Lecture 1 Outline 1. Introduction to computer programming 2. Advanced flow control and data aggregates Your first program First we need to define our expectations for the program. They

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

The Warhol Language Reference Manual

The Warhol Language Reference Manual The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007 Course Web Site http://www.nps.navy.mil/cs/facultypages/squire/cs2900 All course related materials will be posted

More information

Preview from Notesale.co.uk Page 3 of 79

Preview from Notesale.co.uk Page 3 of 79 ABOUT THE TUTORIAL Computer Prgramming Tutorial Computer programming is the act of writing computer programs, which are a sequence of instructions written using a Computer Programming Language to perform

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement

9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions

More information

DEPARTMENT OF MATHS, MJ COLLEGE

DEPARTMENT OF MATHS, MJ COLLEGE T. Y. B.Sc. Mathematics MTH- 356 (A) : Programming in C Unit 1 : Basic Concepts Syllabus : Introduction, Character set, C token, Keywords, Constants, Variables, Data types, Symbolic constants, Over flow,

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators JAVA Standard Edition Java - Basic Operators Java provides a rich set of operators to manipulate variables.

More information

Expr Language Reference

Expr Language Reference Expr Language Reference Expr language defines expressions, which are evaluated in the context of an item in some structure. This article describes the syntax of the language and the rules that govern the

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance. 2.1 Introduction (No questions.) 2.2 A Simple Program: Printing a Line of Text 2.1 Which of the following must every C program have? (a) main (b) #include (c) /* (d) 2.2 Every statement in C

More information

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de

More information

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

And Parallelism. Parallelism in Prolog. OR Parallelism

And Parallelism. Parallelism in Prolog. OR Parallelism Parallelism in Prolog And Parallelism One reason that Prolog is of interest to computer scientists is that its search mechanism lends itself to parallel evaluation. In fact, it supports two different kinds

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes. 10th ICSE. Saravanan Ganesh Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

More information

ARG! Language Reference Manual

ARG! Language Reference Manual ARG! Language Reference Manual Ryan Eagan, Mike Goldin, River Keefer, Shivangi Saxena 1. Introduction ARG is a language to be used to make programming a less frustrating experience. It is similar to C

More information

DaMPL. Language Reference Manual. Henrique Grando

DaMPL. Language Reference Manual. Henrique Grando DaMPL Language Reference Manual Bernardo Abreu Felipe Rocha Henrique Grando Hugo Sousa bd2440 flt2107 hp2409 ha2398 Contents 1. Getting Started... 4 2. Syntax Notations... 4 3. Lexical Conventions... 4

More information

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

4 Programming Fundamentals. Introduction to Programming 1 1

4 Programming Fundamentals. Introduction to Programming 1 1 4 Programming Fundamentals Introduction to Programming 1 1 Objectives At the end of the lesson, the student should be able to: Identify the basic parts of a Java program Differentiate among Java literals,

More information

Advanced Algorithms and Computational Models (module A)

Advanced Algorithms and Computational Models (module A) Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34 Python's built-in classes A class is immutable if each object of that class has a xed value

More information

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators

Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operators Overview Will introduce various operators supported by C language Identify supported operations Present some of terms characterizing operators Operands and Operators Mathematical or logical relationships

More information

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

PART I.   Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++. Unit - III CHAPTER - 9 INTRODUCTION TO C++ Choose the correct answer. PART I 1. Who developed C++? (a) Charles Babbage (b) Bjarne Stroustrup (c) Bill Gates (d) Sundar Pichai 2. What was the original name

More information

Reserved Words and Identifiers

Reserved Words and Identifiers 1 Programming in C Reserved Words and Identifiers Reserved word Word that has a specific meaning in C Ex: int, return Identifier Word used to name and refer to a data element or object manipulated by the

More information

.Net Technologies. Components of.net Framework

.Net Technologies. Components of.net Framework .Net Technologies Components of.net Framework There are many articles are available in the web on this topic; I just want to add one more article over the web by explaining Components of.net Framework.

More information

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309 A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48

More information

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O Overview of C Basic Data Types Constants Variables Identifiers Keywords Basic I/O NOTE: There are six classes of tokens: identifiers, keywords, constants, string literals, operators, and other separators.

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

This tutorial provides a basic level understanding of the LOLCODE programming language.

This tutorial provides a basic level understanding of the LOLCODE programming language. i About the Tutorial LOLCODE is an esoteric programming language inspired by the funny things on the Internet. LOLCODE is designed to test the boundaries of programming language design. This tutorial provides

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Programming Paradigms

Programming Paradigms PP 2017/18 Unit 15 Concurrent Programming with Erlang 1/32 Programming Paradigms Unit 15 Concurrent Programming with Erlang J. Gamper Free University of Bozen-Bolzano Faculty of Computer Science IDSE PP

More information

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called

CS109A ML Notes for the Week of 1/16/96. Using ML. ML can be used as an interactive language. We. shall use a version running under UNIX, called CS109A ML Notes for the Week of 1/16/96 Using ML ML can be used as an interactive language. We shall use a version running under UNIX, called SML/NJ or \Standard ML of New Jersey." You can get SML/NJ by

More information

Work relative to other classes

Work relative to other classes Work relative to other classes 1 Hours/week on projects 2 C BOOTCAMP DAY 1 CS3600, Northeastern University Slides adapted from Anandha Gopalan s CS132 course at Univ. of Pittsburgh Overview C: A language

More information

Bits, Words, and Integers

Bits, Words, and Integers Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information