sverma / funErl

Just some erlang basics and Fun

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Erlang Shell

You can start erlang shell via 'erl' command .

[saurabh.ve@serenity]~% erl
Erlang (BEAM) emulator version 5.6.5 [source] [64-bit] [smp:8] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.6.5  (abort with ^G)
1> 

Variables

Variable should start with either '_' or a capital letter .

  • You can only assign a value to a variable once unless you trying out erlang shell which has function f(variable) to erase the variable.
  • The = operator (not the variables) has the role of comparing values and complaining if they're different. If they're the same, it returns the value:

Atoms

Atoms are literals, constants with their own name for value.

  • Atoms start with 'LOWERCASE' letters , Ohk so thats the reason variables starts with 'UPPERCASE' letters .

  • An atom should be enclosed in single quotes (') if it does not begin with a lower-case letter or if it contains other characters than alphanumeric characters, underscore (_), or @.

  • an atom is referred to in an "atom table" which consumes memory (4 bytes/atom in a 32-bit system, 8 bytes/atom in a 64-bit system).

  • The atom table is not garbage collected, and so atoms will accumulate until the system tips over, either from memory usage or because 1048577 atoms were declared.

    6> saurabh = 'saurabh.ve'. ** exception error: no match of right hand side value 'saurabh.ve' 7> saurabh = 'saurabh'. saurabh 8> saurabh. saurabh

Camparisons

Operators : 'and' , 'or' ( always evaluate arguments on both sides of the operator ) '=:=' or ' =/=' is testing inequlity or equality. '=:=' will test for equality. '=/=' will test against equality. '==' will test for arthemitic equality ( differentiating between floats and integars ) '/=' will against arthemitic equality ( differentiating between floats and integars )

14> saurabh =:= saurabh1.
false
16>14=:=14.
true

Other operators for comparisons are < (less than), > (greater than), >= (greater than or equal to) and =< (less than or equal to)

23> 10>20.
false
24> 10<20.
true
25> 10 >=10.
true
26> 10 =< 10.
true
27> 10 == saurabh.
false

IMP: Erlang has no such things as boolean true and false . The terms true and false are atoms . correct ordering of each element in a comparison is the following: number < atom < reference < fun < port < pid < tuple < list < bit string

Tuples

A tuple is a way to organize data. To group together many terms when you know how many there are. In Erlang, a tuple is written in the form {Element1, Element2, ..., ElementN}.

29> FirstName = 'Saurabh' , LastName = 'Verma'.
'Verma'
30> Name = {FirstName,LastName}.
{'Saurabh','Verma'}

We can extract Elements from a tuple by assigning a tuple to a set of unbound varibles , '=' operator compares both LHS and RHS and assigns the values to LHS if they are unbound variables

32> Name = {'Saurabh','Verma'}.
{'Saurabh','Verma'}
33> {FirstName,LastName} = Name.
{'Saurabh','Verma'}
34> FirstName.
'Saurabh'
35> LastName.
'Verma'

Lists

Lists can contain anything! Numbers, atoms, tuples, other lists . The basic notation of a list is [Element1, Element2, ..., ElementN] and you can mix more than one type of data in it.

40> ['Saurabh' , 'Verma' , {age,26} , male ].
['Saurabh','Verma',{age,26},male]

IMP: Erlang: strings! Strings are lists and the notation is absolutely the exact same!, Ok strings in Erlang is list of Numbers and Erlang will print a list of numbers as numbers only when atleast one of them couldn't represent a letter .

42> [97,98,99,4,5,6].
[97,98,99,4,5,6]
43> [97,98,99,104,105,106].
"abchij"

            There is no such thing as a real string in Erlang! OOOpps 

Operations on Lists

  • Glue operator : '++' , glues two lists together ** Both ++ and -- are right-associative.

    48> [1,2,3] ++ [4,5]. [1,2,3,4,5] 49> [1,2,3,4,5] -- [1,2,3]. [4,5] 50> [1,2,3] -- [1,2] -- [3]. [3]

The first element of a list is named the Head, and the rest of the list is named the Tail.

51> hd([1,2,3,4]).
1
52> tl([1,2,3,4]).
[2,3,4]

hd and tl are builtin functions to get them .

Manipulations on head of lists can be performed via the help of pattern matching [Head|Tail]

Example

53> List = [1,2,3,4,5,6].
[1,2,3,4,5,6]
54> List.
[1,2,3,4,5,6]
55> NewList = [1|List].
[1,1,2,3,4,5,6]

'|' is actually termed as construction operator , Any list can be built with construction operator ('con') and values

62> ['saurabh','verma',1,[2,3,4],[]].
[saurabh,verma,1,[2,3,4],[]]

List can be built with the formula : [Term1|[Term2 | [Term3 | [....]]]]

List Comprehensions

List comprehensions are ways to build or modify lists

List comprehensions are actually based on the idea of set notations , Example { x ∈ R: x = x²} which would result to {0,1} Also lets say { x ∈ R: x > 10 } which would result in all real numbers greater than 10.

List comprehensions are about building sets from other sets , For example "Double each element of set" {2n: n in List} , which List is [2,4,5,6] , The erlang implementation would be

63> [2*N || N <- [2,4,5,6]].
[4,8,10,12]

Adding constraints to a list comprehension is done using operations that return boolean values , Lets say we want to find all odd numbers between 20 and 30.

67> [N || N <- [20,21,22,23,24,25,26,27,28,29,30], N rem 2 =:= 0].
[20,22,24,26,28,30]

We can apply a function to each element of a list , forcing it to respect constraints. Lets say , you want to all games in a gaming shop which are priced less than $200 with taxes (say 7%).

69> GamesMenu = [{godOfwar,300} , {heavenlySword,150} , {dirt3,100} , {godOfWar,400} , {gT5,189}.
[{godOfwar,300},
 {heavenlySword,150},
 {dirt3,100},
 {godOfWar,400},
 {gT5,189}]
70> [{Game,Price*1.07} || {Game,Price} <- GamesMenu, Price < 200 ].
[{heavenlySword,160.5},
 {dirt3,107.0},
 {gT5,202.23000000000002}]

The recipe for list comprehensions in Erlang is therefore NewList = [Expression || Pattern <- List, Condition1, Condition2, ... ConditionN]

Patten <- List is named as generator expression , You can have more than one .

85> [X+Y || X <- [1,2] , Y <- [2,3]].
[3,4,4,5]

Generic form of List comrehension can be expressed as NewList = [Expression || GeneratorExp1, GeneratorExp2, ..., GeneratorExpN, Condition1, Condition2, ... ConditionM]

h3. Note that the generator expressions coupled with pattern matching also act as a filter:

86> GameType = [{godOfwar, fantasyAction} , {heavenlySword,fantasyAction} , {dirt3,racing} , {gT5,racing} ].
[{godOfwar,fantasyAction},
 {heavenlySword,fantasyAction},
 {dirt3,racing},
 {gT5,racing}]
87> RacingGames = [ Game || {Game,racing} <- GameType].
[dirt3,gT5]

Dealing with Bits

Erlang makes dealing with raw binary data fun and easy , Bit syntax encloses binary data between << and >> , splits it in readable segments, and each segment is separated by a comma. A segment is a sequence of bits of a binary.

Example :

Orange Color is equal to "#F09A29" in hexadecimal notation .

88> Orange= 16#F09A29.
15768105


90> Pixel = <<Orange:24>>.
<<240,154,41>>

The above code puts the binary values of "#F09A29" on 24 bits of space in the variable Pixel.

Pattern Matching with Binaries

91> Pixels = <<213,45,132,64,76,32,76,0,0,234,32,15>>.
<<213,45,132,64,76,32,76,0,0,234,32,15>>
92> <<Pix1,Pix2,Pix3,Pix4>> = Pixels.
** exception error: no match of right hand side value <<213,45,132,64,76,32,76,0,0,234,32,15>>
93> <<Pix1:24, Pix2:24, Pix3:24, Pix4:24>> = Pixels.
<<213,45,132,64,76,32,76,0,0,234,32,15>>
94> Pix1.
13970820

Var:24 means that the variable will hold 24 bits of data, since Pixels variables hold 4 pixels of RGB colors in binary the total segments (12) didn't match the number of the segments in the second statement (4) .

You can use more than on way to describe a binary segments :

Value
Value:Size
Value/TypeSpecifierList
Value:Size/TypeSpecifierList

Example

<<213,45,132,64,76,32,76,0,0,234,32,15>>
99> R.                                              
213
100> Rest.
<<45,132,64,76,32,76,0,0,234,32,15>>

About

Just some erlang basics and Fun


Languages

Language:Erlang 100.0%