Practical Erlang Programming Basic Erlang. © 2001 -2009 Erlang Training and Consulting Ltd2Basic Erlang Practical Erlang Programming.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms
Advertisements

Programming Languages and Paradigms The C Programming Language.
Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Introducing the Erlang Language Why Erlang?  Exemplifies the “you can have code and concurrency that is free from side effects…there is no other way”
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
CS241 PASCAL I - Control Structures1 PASCAL I - Control Structures Philip Fees CS241.
JavaScript, Third Edition
VB .NET Programming Fundamentals
Basic Elements of C++ Chapter 2.
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
The Data Element. 2 Data type: A description of the set of values and the basic set of operations that can be applied to values of the type. Strong typing:
CIS Computer Programming Logic
17-Sep-15 Erlang. Running Erlang Double-click on the Erlang icon, or type erl into a terminal (cmd) window You can try short pieces of code from here,
JavaScript – Part II Data Types and Operations George Mason University June 3, 2010.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
ERLANG Bruno Bourbon Gilberto Alves. Introdução Grades sistemas de telecomunicação são um grande desafio da programação: –Distribuidos –Concorretes –Tolerantes.
Chapter 2 Overview of C++. A Sample Program // This is my first program. It calculates and outputs // how many fingers I have. #include using namespace.
CPS120: Introduction to Computer Science
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
C++ Programming: Basic Elements of C++.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Introduction to Java Java Translation Program Structure
Copyright Curt Hill Variables What are they? Why do we need them?
JavaScript, Fourth Edition
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Chapter 5 Introduction to VHDL. 2 Hardware Description Language A computer language used to design circuits with text-based descriptions of the circuits.
CS241 PASCAL I - Control Structures1 PASCAL Control Structures Modified Slides of Philip Fees.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Expressions and Data Types Professor Robin Burke.
Erlang - a complete development environment for concurrent programming RTLab. Kim Tae-Hyon.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter VII: Arrays.
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
CSc 120 Introduction to Computer Programing II Adapted from slides by
Documentation Need to have documentation in all programs
Multiple variables can be created in one declaration
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Programmazione I a.a. 2017/2018.
Erlang 15-Nov-18.
IDENTIFIERS CSC 111.
Variables Numbers can be stored and retrieved while a program is running if they are given a home. The way that integers and decimal numbers are stored.
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
CMSC 202 Java Primer 2.
Basic Syntax and Semantics
Program Breakdown, Variables, Types, Control Flow, and Input/Output
High Level Programming Languages
The Data Element.
The Data Element.
Presentation transcript:

Practical Erlang Programming Basic Erlang

© Erlang Training and Consulting Ltd2Basic Erlang Practical Erlang Programming

© Erlang Training and Consulting Ltd3Basic Erlang Overview: Basic Erlang I Basic Erlang I  Data Types  Variables  Complex Data Structures  Pattern Matching Basic Erlang II

© Erlang Training and Consulting Ltd4Basic Erlang Data Types: Integers #AB10F 2# $A B#Val is used to store numbers in base $Char is used for ascii values  example $A instead of 65 Large integers are converted to bignums Max size depends on physical constraints  RAM  paging memory

© Erlang Training and Consulting Ltd5Basic Erlang Data Types: Floats E-10 Not efficiently implemented Stored as a double  64-bit representation Follows the IEEE 754 standard

© Erlang Training and Consulting Ltd6Basic Erlang Data Types: Atoms person start_with_a_lower_case_letter 'Blanks can be quoted' 'Anything inside \n\012' Atoms are constant literals Start with a lower case letter or are encapsulated by ’ ’ Any character code is allowed within an atom if using ’ ’ Letters integers and _ are allowed if the atom starts with a lower case letter

© Erlang Training and Consulting Ltd7Basic Erlang Data Types: Tuples {123, bcd} {123, def, abc} {person, 'Joe', 'Armstrong'} {abc, {def, 123}, jkl} {} Tuples are used to store a fixed number of items Tuples of any size are allowed Contain valid Erlang expressions

© Erlang Training and Consulting Ltd8Basic Erlang Data Types: Lists [1, 2, 3, 4, 5, 6, 7, eight, nine] Used to store a variable number of items Lists are dynamically sized Strings in Erlang are lists of ASCII values Lists are written beginning with a [ and ending with a ] Elements are separated by commas

© Erlang Training and Consulting Ltd9Basic Erlang Data Types: Lists [123, xyz] [123, def, abc] length([a,[b,[c,d,e],f], g]) == 3. [{person, 'Joe', 'Armstrong'}, {person, 'Robert', 'Virding'}, {person, 'Mike', 'Williams'} ] "abcdefghi” == [97,98,99,100,101,102,103,104,105] ”” == [] [1 | [2 | [3 | [4 | []]]]] == [1,2,3|[4]] == [1,2,3,4]

© Erlang Training and Consulting Ltd10Basic Erlang Data Types: Lists List =[Element | List] or [] A recursive list definition consists of a head and a tail Lists whose last Tail term is [] are called:  proper lists or  well formed lists The Tail can be any valid Erlang datatype Most Erlang programs manipulate proper lists

© Erlang Training and Consulting Ltd11Basic Erlang Data Types: Lists String Concatenation “ABC” “DEF” == “ABCDEF” List Concatenation [1,2,3] ++ [4,5,6] == [1,2,3,4,5,6] List Subsets [1,2,3,4] -- [2,3] == [1,4]

© Erlang Training and Consulting Ltd12Basic Erlang Variables Abc A_long_variable_name AnObjectOrientatedVariableName _a_do_not_care_variable _ Variables start with an Upper Case Letter or _ They may not contain any “funny characters” _ alone is a don’t care variable  Its values are ignored and never bound

© Erlang Training and Consulting Ltd13Basic Erlang Variables Variables are used to store values of data structures The value of a variable can not be changed once it has been bound There is no need to declare them. Just use them! Erlang does not have a type system Types are determined at run time Variables can only be bound once!

© Erlang Training and Consulting Ltd14Basic Erlang Complex Data Structures [{{person,'Joe', 'Armstrong'}, [{telephoneNumber, [3,5,9,7]}, {shoeSize, 42}, {pets, [{cat, tubby},{cat, tiger}]}, {children,[{thomas, 5},{claire,1}]}] }, {{person,'Mike','Williams'}, [{shoeSize,41}, {likes,[boats, beer]}] } ].

© Erlang Training and Consulting Ltd15Basic Erlang Complex Data Structures Arbitrary complex structures can be created by nesting other data structures Data structures may contain bound variables Data structures are created by writing them down No explicit memory allocation or deallocation is needed  Allocated automatically  Deallocated by the Garbage Collector when no longer referenced

© Erlang Training and Consulting Ltd16Basic Erlang Pattern = Expression Pattern Matching Pattern Matching is used for: Assigning values to Variables Controlling the execution flow of the programs Extracting values from compound data types

© Erlang Training and Consulting Ltd17Basic Erlang Pattern Matching: Assigning The Pattern can contain unbound variables which are bound when the pattern matching succeeds The Expression may not contain unbound variables A = 10 Succeeds: binds A to 10 {B, C, D} = {10, foo, bar} Succeeds: binds B to 10, C to foo and D to bar {E, E, foo} = {abc, abc, foo} Succeeds: binds E to abc [H|T] = [1,2,3] Succeeds: binds H to 1, T to [2,3]

© Erlang Training and Consulting Ltd18Basic Erlang Pattern Matching: Testing A match must either succeed or fail Used to pick the execution flow in:  case statements  receive statements  function heads {A, A, B} = {abc, def, 123} Fails [A,B,C,D] = [1,2,3] Fails [A,B|C] = [1,2,3,4,5,6,7] Succeeds: binds A = 1, B = 2, C = [3,4,5,6,7] [H|T] = [] Fails

© Erlang Training and Consulting Ltd19Basic Erlang Pattern Matching: Extracting Used to extract values from complex data types Note the use of _, the don't care variable {A,_, [B|_],{B}} = {abc,23,[22,x],{22}} Succeeds: binds A = abc, B = 22 C = 10, {C, C, 13, D, _} = {10,10,13,12,15} Succeeds: Binds D = 12 and C = 10 Var = {person, ‘Francesco’, ‘Cesarini’}, {person, Name, Surname} = Var Succeeds: binds Name = ‘Francesco’, Surname = ‘Cesarini’ [Element|Tail] = [1,2,3,4] Succeeds: binds Element = 1, Tail = [2,3,4]

© Erlang Training and Consulting Ltd20Basic Erlang Summary: Basic Erlang I Basic Erlang I  Data Types  Variables  Complex Data Structures  Pattern Matching Basic Erlang II

© Erlang Training and Consulting Ltd21Basic Erlang Overview: Basic Erlang II Basic Erlang I Basic Erlang II  Function Calls  Modules  Starting the System

© Erlang Training and Consulting Ltd22Basic Erlang Functions: Syntax area({square, Side}) -> Side * Side ; area({circle, Radius}) -> 3.14 * Radius * Radius; area({triangle, A, B, C}) -> S = (A + B + C)/2, math:sqrt(S*(S-A)*(S-B)*(S-C)) ; area(Other) -> {error, invalid_object}. function clauses function head expression separator function separator clause separator ; ; function body

© Erlang Training and Consulting Ltd23Basic Erlang Functions: Calls Module:Function(Arg1, Arg2,... ArgN) Function(Arg1, Arg2,.. ArgN) Erlang programs consist of functions that call each other Functions are defined within Modules Function and module names must be atoms The arity of a function is its number of arguments

© Erlang Training and Consulting Ltd24Basic Erlang Functions: Syntax Func(Pattern1, Pattern2,...) ->, …… ; Func(Pattern1, Pattern2,...) ->, …… ; …… Func(Pattern1, Pattern2,...) ->, ……. A function is defined as a collection of clauses Variables are pattern matched in the function head If pattern matching fails on a clause, the next one is tested  One clause must always succeed Functions return value of the last expression executed

© Erlang Training and Consulting Ltd25Basic Erlang factorial(0) -> 1; factorial(N) -> N * factorial(N-1). > factorial(3). (matches N = 3 in clause 2) == 3 * factorial(3 - 1) (matches clause 2) == 3 * 2 * factorial(2 - 1) (matches clause 2) == 3 * 2 * 1 * factorial(1 - 1) (matches clause 1) == 3 * 2 * 1 * 1 = 6 Pattern Matching occurs in the function head  Unbound variables get bound after a successful pattern match Variables are local to each clause Variables are allocated and deallocated automatically Functions: Examples

© Erlang Training and Consulting Ltd26Basic Erlang Modules Modules are stored in files with the.erl suffix The module and file names must be the same  Modules are named with the -module(Name). directive Exported functions can be called from outside the module  Export them with  -export([Function/Arity, Function/Arity, …])  Use the module prefix when making the call Local functions may only be called within the module

© Erlang Training and Consulting Ltd27Basic Erlang -module(demo). -export([double/1]). % This is a comment. % Everything after % is ignored! double(X) -> times(X, 2). times(X, N) -> X * N. Modules module directivesmodule name exported functions functions arity

© Erlang Training and Consulting Ltd28Basic Erlang Starting the System Start the Erlang system by typing erl in the unix shell, or double clocking on the Erlang icon in Windows. An Erlang shell will be started. 1>, 2> … are shell prompts. The shell is an Erlang process that sits in a read-eval-print loop. It reads valid Erlang expressions typed in by the user and evaluates them. c(File) compiles the file File.erl and loads the module in the shell. Ensure the current shell directory is in the same as the location of the module you are compiling.  Use cd(“Path”) and pwd() In the shell.

© Erlang Training and Consulting Ltd29Basic Erlang Eshell V5.0.1 (abort with ^G) 1> c(demo). {ok, demo} 2> demo:double(25). 50 3> demo:times(4,3). ** exited: {undef,{demo,times,[4,3]}} ** 4> >

© Erlang Training and Consulting Ltd30Basic Erlang Exercise Write a module boolean.erl that takes logical expressions and boolean values (represented as the atoms true and false) and returns their boolean result. The functions you should write should include b_not/1, b_and/2, b_or/2, b_nand/2. You may not use the logical constructs and, or or not. Test your module from the shell. Interface: b_not(false)  true b_and(false, true)  false b_and(b_not(b_and(true, false)), true)  true Note 1: foo(X)  Y means that calling the function foo with the parameter X will result in the value Y being returned. Note 2: and, or and not are reserved words in Erlang.

© Erlang Training and Consulting Ltd31Basic Erlang Summary: Basic Erlang II Basic Erlang I Basic Erlang II  Function Calls  Modules  Starting the System