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,

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

OJ Reeves. Agenda  The Boring Stuff Basic syntax, expressions, funcs, records Atoms, BIFs, data types, bools, equality  The not so Boring Stuff Pattern.
ES 314 Lecture 2 Sep 1 Summary of lecture 1: course overview intro to matlab sections of Chapters 2 and 3.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Computer Science 1620 Loops.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
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.
Erlang (Condensed) 21-Jun-15. Important concepts in Erlang There is no “assignment”—only pattern matching Pattern matching is like unification All “variables”
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Overview of C++ Chapter 2 in both books programs from books keycode for lab: get Program 1 from web test files.
Introduction to C Programming
Fundamentals of Python: From First Programs Through Data Structures
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
A Review of Programming and C++
Introduction to Python
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Computer Science 101 Introduction to Programming.
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.
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.
Chapter 2: Java Fundamentals
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Built-in Data Structures in Python An Introduction.
Functional Programming With examples in F#. Pure Functional Programming Functional programming involves evaluating expressions rather than executing commands.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Chapter 05 (Part III) Control Statements: Part II.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Practical Erlang Programming Basic Erlang. © Erlang Training and Consulting Ltd2Basic Erlang Practical Erlang Programming.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Testing Abstract Data Structures with QuickCheck Thomas Arts Quviq AB / Chalmers.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Erlang Noah Dietrich Chris Ruffalo.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
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.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real.
Introduction to Objective Caml. General comments ML is a purely functional language--there are (almost) no side effects There are two basic dialects of.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
CS201 Introduction to Sabancı University 1 Chapter 2 Writing and Understanding C++ l Writing programs in any language requires understanding.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
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.
C++ First Steps.
Definition of the Programming Language CPRL
Introduction to C++ Programming
Introduction to Scripting
Erlang 15-Nov-18.
Arithmetic operations, decisions and looping
Introduction to C++ Programming
Basic Syntax and Semantics
Introduction to C++ Programming
Lexical Elements & Operators
Presentation transcript:

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, but you cannot import code or define functions Use c( module.erl). (no quote marks) to compile a module named module from the file module.erl. To use a function func defined in module.erl, use module : func ( args ) Use f(). to clear (forget) previous associations. Use the up and down arrows to choose a previous entry. Use control-C to exit the shell. 2

Directives An Erlang program should begin with -module( filename ). where filename.erl is the name of the file it is on To use functions defined in another file, use -import( filename, [ function1 / arity1,..., functionN / arityN ]). Imported methods may be called without a filename : prefix. To provide functions defined in this file to other programs, use either of -export( filename, [ function1 / arity1,..., functionN / arityN ]). -compile(export_all).

Names Variables begin with a capital letter or an underscore The special variable _ is the “don’t care” variable Variables are either bound (have a value) or unbound; once bound, they cannot be changed Function names and atoms begin with a lowercase letter An atom is a word that stands for itself

Data types Integers, of unlimited size: Floats: , e23 Strings, enclosed in double quotes: "This is a string." A string is implemented as a list of ASCII (integer) values Atoms: atom1, 'Atom 2' Begin with a lowercase letter, or are enclosed in single quotes Lists: [abc, 123, "pigs in a tree"] Tuples: {abc, 123, "pigs in a tree"} Binaries: >, >, > Binaries exactly specify bits The number of bits in a binary must be a multiple of 8.

Operations Arithmetic: +X -X X * Y X / Y X div Y X rem Y X + Y X - Y Comparison: X = Y X > Y Only for comparing integers and floats: X == Y X /= Y Boolean: not X X and Y X or Y X andalso Y X orelse Y Bitwise: bnot X X band Y X bor Y X bxor Y X bsl Y X bsr Y

Pattern matching Pattern matching looks like assignment: pattern = expression The pattern may be a constant, a bound or unbound variable, or a structure (such as a list or tuple) containing these Example: {ok, Stream} = file:open(FileName, write) Although pattern matching isn’t assignment, Erlang is one of a number of so-called “single assignment” languages

Case expressions case Expression of Pattern1 when Guard1 -> Expression_sequence1 ; Pattern2 when Guard2 -> Expression_sequence2 ;... PatternN when GuardN -> Expression_sequenceN end The when Guard parts are optional boolean tests An expression sequence is a sequence of expressions separated by commas The value of a case expression is the value of the (one) expression sequence evaluated The value of an expression sequence is the value of the last expression evaluated Semicolons must be exactly as shown: Required after every case except the last, not allowed after the last case

If expressions if Guard1 -> Expression_sequence1 ; Guard2 -> Expression_sequence2 ;... GuardN -> Expression_sequenceN end The value of an if expression is the value of the (one) expression sequence evaluated In Erlang, every statement must have a value, or it is an error Frequently true is used as the last guard However, it is good style to use something more explicit than true, if you can easily do so

Guards Guards may not have side effects You cannot use a user-defined function in guards You can use type tests, boolean operators, bitwise operators, arithmetic operators, relational operators Here is the complete list of functions you can use in guards: abs( Number ) hd( List ) node( X ) size( TupleOrBinary ) element( Integer, Tuple ) length( List ) round( Number ) trunc( Number ) float( Number ) node() self() tl( List )

Named functions The syntax for a named function is a series of one or more clauses: name ( Patterns1 ) -> Expression_sequence1 ; name ( Patterns2 ) -> Expression_sequence2 ;... name ( PatternsN ) -> Expression_sequenceN. where The name and the arity are the same for each clause Clauses are tried in order until one of the parameter lists (sequence of patterns) matches, then the corresponding expression sequence is evaluated The value of the function is the value of the expression sequence that is evaluated It is an error if no parameter list matches.

Anonymous functions The syntax for an anonymous function is fun( Patterns1 ) -> Body1 ; ( Patterns2 ) -> Body2 ;... ( PatternsN ) -> BodyN end Anonymous functions are frequently used as parameters to other functions

Lists The values in a list may be of different types. Example: [5, "abc", [3.2, {a, >}] A list comprension has the syntax [ Expression || Generator, GuardOrGenerator,..., GuardOrGenerator ] where The Expression typically makes use of variables defined by a Generator A Generator provides a sequence of values; it has the form Pattern <- List A Guard is a test that determines whether the value will be used in the Expression At least one Generator is required; Guards and additional Generators are optional Example list comprehension: N = [1, 2, 3, 4, 5]. L = [10 * X + Y || X <- N, Y <- N, X < Y]. % Result is [12,13,14,15,23,24,25,34,35,45]

List operations The following list operations are predefined: hd( List ) -> Element Returns the first element of the list tl( List ) -> List Returns the list minus its first element length( List ) -> Integer Returns the length of the list To use other list functions, either: List the functions in an import directive, or Prefix each function name with lists:

More list operations seq( From, To ) -> Seq Returns a sequence of integers from From to To, inclusive map( Fun, List1 ) -> List2 Takes a function from As to Bs, and a list of As and produces a list of Bs by applying the function to every element in the list The evaluation order is implementation dependent Example: lists:map(fun(X) -> 2 * X end, [1, 2, 3]). % Result is [2,4,6] filter( Pred, List1 ) -> List2 List2 is a list of all elements Elem in List1 for which Pred(Elem) returns true Example: lists:filter(fun(X) -> X =< 3 end, [3, 1, 4, 1, 6]). % Result is [3,1,1] foldl( Fun, Acc0, List ) -> Acc1 Calls Fun(Elem, AccIn) on successive elements A of List, starting with AccIn == Acc0 Fun/2 must return a new accumulator which is passed to the next call The function returns the final value of the accumulator, orAcc0 is returned if the list is empty Example: lists:foldl(fun(X, Y) -> X + 10 * Y end, 0, [1, 2, 3, 4, 5]). % Result is 12345

Input/Output Input from the console: Line = io:get_line( Prompt ). An atom is best used as a prompt; returns a string ending in \n Term = io:read( Prompt ). Reads in one Erlang term, which must be terminated with a period Output to the console: io:format( StringToPrint ). io:format( FormatString, ListOfData ). Input from a file: {ok, Stream } = file:open( FileName, read), Line = io:get_line( Stream, ''), % May return eof file:close( Stream ). Output to a file: {ok, Stream } = file:open( FileName, write), io:format( Stream, FormatString, ListOfData ), file:close( Stream ).

Format strings On output, data is interpolated (inserted) into the FormatString at the following locations (excluding ~n ): ~s Print as a string ~w Print any value in "standard syntax“ Strings are printed as lists of integers ~p Pretty print any value (breaking lines, indenting, etc.) ~n Print a newline (you can also use \n ) Comments begin with a % and extend to the end of the line

A first example -module(ex). -compile(export_all). factorial(1) -> 1; factorial(N) -> N * factorial(N - 1). 3> c(ex.erl). {ok,ex} 4> ex:factorial(10) > ex:factorial(100) > 18

Useful URLs The Erlang reference manual: OTP Reference Page Index: Learn You Some Erlang for Great Good A Concise Guide to Erlang /ConciseGuides/concise-erlang.html

The End