Erlang is a programming language for building highly parallel, distributed, fault-tolerant systems. This is the second part of a two-part introduction.
On March 2014, Java 8 was released. These informal slides describe the new elements of the programming languages, focusing on those taken from the functional paradigm.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Erlang is a programming language for building highly parallel, distributed, fault-tolerant systems. This is the second part of a two-part introduction.
On March 2014, Java 8 was released. These informal slides describe the new elements of the programming languages, focusing on those taken from the functional paradigm.
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
Object-Oriented Programming has well established design principles, such as SOLID. For many developers architecture and functional programming are at odds with each other: they don’t know how their existing tricks of the trade convert into functional design. This problem becomes worse as hybrid languages such as Java 8 or Scala become common. We’ll talk about how functional programming helps you implement the SOLID principles, and how a functional mindset can actually help you achieve cleaner and simpler OO design.
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
In a nutshell, an Arduino is an open hardware development board that can be used by tinkerers, hobbyists, and makers to design and build devices that interact with the real world. While Arduino refers to a specific type of board design, it can also be used to refer to a company which manufactures a specific implementation of these boards, and is typically also used to describe the community around compatible boards made by other people or companies which function in a similar way.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
In a nutshell, an Arduino is an open hardware development board that can be used by tinkerers, hobbyists, and makers to design and build devices that interact with the real world. While Arduino refers to a specific type of board design, it can also be used to refer to a company which manufactures a specific implementation of these boards, and is typically also used to describe the community around compatible boards made by other people or companies which function in a similar way.
Soviet Popular Music Landscape: Community Structure and Success PredictorsDmitry Zinoviev
More than 4,600 non-academic music groups emerged in the USSR and post-Soviet independent nations in 1960–2015, performing in 275 genres and sub-genres, including rock, pop, disco, jazz, and folk. Some of the groups became legends and survived for decades, while others vanished and are known now only to select music history scholars and fans. The total number of unique performers in all groups exceeds 17,000, and at least 3,600 of them participated in more than one project.
QCON SP 2016 - Elixir: Tolerância a Falhas para AdultosFabio Akita
Elixir é uma das novas linguagens que está despontando principalmente pela reputação de capacidade de altíssima concorrência e paralelismo que sua VM permite. Mas o principal elemento é que Erlang e por consequência, Elixir, é uma das poucas linguagens criadas assumindo que vamos cometer erros. Ele garante alta disponibilidade nos dando primitivas que permitam que nosso software continue funcionando, mesmo que às vezes ele falhe. E agora vamos ver como Erlang faz isso como Elixir expõe esse potencial a todos nós.
Parsing binaries and protocols with erlangBhasker Kode
Delivered by Bhasker V Kode at foss.in/2009
Official talk page at http://foss.in/2009/schedules/talkdetailspub.php?talkid=17
Erlang 's support for handling binaries and pattern matching make it a great choice for parsing everything from IPv4 packets, to payloads from the Memcached protocol, SWF files, or databases like Tokyo Cabinet. From a functional programming perspective, there are various ways of building these parsers, taking advantage of the concurrent and recursive nature that is inherent to the language and other challenges which have been gathered while validating the storage & retrieval options for our distributed crawler, and submitting patches to projects like Medici & Tora ( erlang based Tokyo Cabinet clients). The talk will also touch upon Tokyo cabinet's support for mapreduce with Lua, and notes from building your own custom formats & our internal mapreduce'esque and caching frameworks used in building a multi-million impression platform utilizing under a gig of RAM per node.
Notes on:
- trends in disk/memory/bandwidth
- why erlang, RAM, binaries
- garbage collection in the erlang VM
- message passing
- use-cases
- Basics: BEAM Ecosystem and Erlang Programming Language
- Functional Programming: How Make your code Beautiful
- Concurrency: You need to be concurrent to survive in the parallel world
- Fault Tolerance: Keep calm and let it crash
- Soft Real-time: Accept the reality, be real, be yourself
- Software Architecture: How to look nice in a bigger picture
An introduction to the OpenMP parallel programming model.
From the Scalable Computing Support Center at Duke University (http://wiki.duke.edu/display/scsc)
Check out these exercises: http://de.slideshare.net/nicolayludwig/3-cpp-procedural-programmingexercises
- Procedural Programming
- Predefined and User defined Functions
- Declaration and Definition of Functions
- Procedural and recursive Function Calling
- Namespaces and separated Function Definitions
- A Glimpse of Separated Compilation and Translation Units
Using Complex Network Analysis for PeriodizationDmitry Zinoviev
Periodization is the process of categorizing the past into discrete, contiguous, quantified, and named blocks of time and the results of such a process. I propose to model historical states as complex networks and use complex network analysis (CNA) for periodization.
The majority of the USA population still believe people with serious mental illness (SMI) are dangerous. SMI and dangerousness have been recurring topics of newspaper coverage for some time. What aspects, if any, have been associated in mainstream American media with SMI? Are there historical periods where significant sociopolitical events have occurred e.g., war, economic depression, immigration shifts, that have impacted the balance of positive and negative those aspects?
Roles and Words in a massive NSSI-Related Interaction NetworkDmitry Zinoviev
Non-suicidal self-injury (NSSI), such as self-cutting or self-burning, is the deliberate destruction of one’s body tissue in the absence of suicidal intent. Approximately one in five of adolescents and one in four of young adults in the USA often referred to as “self-cutters,” have engaged in NSSI. The goal of the study is to analyze the topology of an interaction network of the NSSI-related users and compare it to the vocabulary of the blog posts and comments.
Network analysis of the 2016 USA presidential campaign tweetsDmitry Zinoviev
This is an IC2S2 presentation.
Donald Trump has been an avid user of Twitter before, throughout, and in the aftermath of the 2017 USA presidential election campaign. Secretary Hillary Clinton, the Democratic Party candidate, was active on Twitter only from the beginning to end of the campaign. The goal of this research is to reconstruct the timeline and logic of the campaign using complex network analysis of President Trump's and Secretary Clinton's tweets.
We analyzed 20,000 tweets posted by Trump in January 2014--December 2017, covering all three major stages of his quest for the Presidency. The tweets are composed of 14,373 distinct, unstemmed terms (words, word combinations, and hashtags). For further analysis, we selected only 300 base terms that occurred in the whole corpus at least 100 times. We grouped the tweets by months into 48 tweet corpora and converted them into a network, based on the similarity of the vocabulary. Each network node represents a monthly corpus. We connected two nodes with a weighted edge if the frequencies of the base terms in the corresponding corpora were strongly correlated (with the Pearson correlation coefficient, serving as the weight of the edge, at or above 0.6).
The corpus consists of two clusters: April 2015 (when Clinton announced her intention to run)--March 2016 and April 2016--November 2016 (the general election). Interestingly, the boundary between the clusters corresponds to the campaign stages, too---but those of Trump rather than Clinton: it is located in the middle of the Republican Party primary elections. We hypothesize that throughout the campaign Secretary Clinton was in the defensive position and had to respond to the challenges posed by Trump, rather than form her agenda (at least on Twitter). We will further look into the cross-correlations between the tweet corpora of the two major presidential candidates to get a better sense of their ``leader-follower'' relationship.
An example of how automated text analysis leads, through social network construction, to recognition of key plot lines and characters in a fiction book.
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
In the ever-evolving landscape of technology, enterprise software development is undergoing a significant transformation. Traditional coding methods are being challenged by innovative no-code solutions, which promise to streamline and democratize the software development process.
This shift is particularly impactful for enterprises, which require robust, scalable, and efficient software to manage their operations. In this article, we will explore the various facets of enterprise software development with no-code solutions, examining their benefits, challenges, and the future potential they hold.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Essentials of Automations: The Art of Triggers and Actions in FME
Introduction to Erlang Part 1
1. What Is Erlang?What Is Erlang?
Erlang is a programming language for building highly parallel,
distributed, fault-tolerant systems.
To start the Erlang interpreter, type erl at the shell prompt. And do not
forget: there is a dot at the end of an Erlang statement, not a
semicolon.
2. Facts about ErlangFacts about Erlang
● “Shared-nothing” model: no shared variables, pure message passing
● Erlang processes run on nodes, nodes run on physical computers
● Pairs of processes can be linked to support termination notification
● Hot-swappable modules (dynamic on-the-fly code replacement)
● Mnesia: built-in distributed fault-tolerant database
● OTP (Open Telecom Platform), a set of libraries and procedures that
includes:
● A complete Web server
● A complete FTP server
● A CORBA ORB
3. Apach vs YawsApach vs Yaws
● Yaws is an Erlang-
based Web server
● The graph shows
thoughput (KB/sec)
vs. load.
● Apache (blue and
green) dies when
subject to a load of
ca. 4000 parallel
sessions.
6. Programming Erlang: the Sequential Part 6
ArithmeticsArithmetics
● Erlang integer numbers are arbitrary-sized (there is no overflow)
● 16#19AC is a base 16 number, 32#SUGAR is a base 32 number, etc.
● / always produces a floating point value; rem and div perform integer
division. 5/2 is 2.5
● bnot, band, bor, bxor, bsl, bsl perform bitwise operations
7. Programming Erlang: the Sequential Part 7
VariablesVariables
● Variables in Erlang are single-assignment (immutable), like final in
Java. Single assignment does not cause side effects and makes
parallelism easy. Variable names begin with an uppercase letter.
● = is not assignment but matching: it matches the LHS against the RHS
and binds variables to the matching values. No weird math like
X=X+1.
● Function f() “forgets” all existing bindings.
8. Programming Erlang: the Sequential Part 8
ExamplesExamples
1> Oranges = 7.
7
2> Apples = 12.
12
3> Apples1 = Apples / 5 + Oranges.
9.4
4> Apples = Apples.
12
5> Oranges = Apples.
** exception error: no match of right hand side value
12
9. Programming Erlang: the Sequential Part 9
AtomsAtoms
● An atom is like a C/Java enum. It begins with a lowercase letter, can
consist of alphanumeric symbols, underscores _, and @. It can also be
any sequence of symbols in single quotation marks.
● The value of an atom is the atom itself.
10. Programming Erlang: the Sequential Part 10
ExamplesExamples
1> Apple.
* 1: variable 'Apple' is unbound
2> apple.
apple
3> 'Apple'.
'Apple'
4> apples@oranges.
apples@oranges.
11. Programming Erlang: the Sequential Part 11
TuplesTuples
● A tuple is a collection of values enclosed in curly braces {}.
● The tuple fields do not have to be homogeneous.
● Tuple fields can be extracted using pattern matching.
● Atom _ matches anything.
13. Programming Erlang: the Sequential Part 13
ListsLists
● A list is an ordered collection of values enclosed in square brackets [].
● A list has a head H (car) and a tail T (cdr). T must be a list (can be an
empty list []).
● Vertical bar | separates H from T: [ H | T ]
● List elements can be extracted by pattern matching.
● Always build lists by adding a head to a tail! Operator ++ is very
slow.
14. Programming Erlang: the Sequential Part 14
ExamplesExamples
1> Food = [{apples,12},{oranges,77},{foobar,3}].
[{apples,12},{oranges,77},{foobar,3}]
2> [Breakfast|MoreFood] = Food.
[{apples,12},{oranges,77},{foobar,3}]
3> Breakfast.
{apples,12}
4> {FruitForBreakfast,_} = Breakfast.
{apples,12}
5> FruitForBreakfast.
apples
15. Programming Erlang: the Sequential Part 15
Other OperatorsOther Operators
● =:= tests for equality
● Boolean operators: and, or, not, xor
● Short-circuit Boolean: orelse, andalso
● ++ (infix) appends lists (should be avoided)
● -- subtracts a list from a list
16. Programming Erlang: the Sequential Part 16
StringsStrings
● A string is a list of integers.
● A string can be also represented as a collection of printable symbols
enclosed into double quotes.
● Operator $ translates a character into its numerical value: $a is 97.
● [$h,$e,$l,$l,$o] is “hello.”
17. Programming Erlang: the Sequential Part 17
ModulesModules
● A module (mymod) is a logically complete piece of code in a file
(mymod.erl).
● Function c() compiles a module into bytecode: c(mymod). produces
file mymod.beam.
● Modules have attributes.
● Attribute -module(mymod). starts the module code.
● Attribute -import(othermod). imports a module.
● Attribute -export([list of funcs]). exports functions.
● Attributes must precede any other code.
18. Programming Erlang: the Sequential Part 18
FunctionsFunctions
● A function consists of one or more clauses with heads and bodies.
● The clauses are separated by a semicolon.
● The order of clauses matters.
● Clauses can be recursive.
● Functions must be declared in modules (not in the shell).
● Functions are polymorphic.
19. Programming Erlang: the Sequential Part 19
ExamplesExamples
-export[area/1].
area ({rectangle, H, W}) → W * H;
area ({circle, R}) → 3.14159 * R * R.
%% Another file!
-export[reduce/1,reduce/0].
reduce ([]) → 0;
reduce ([Head|Tail]) → someFuncOf (Head)
+ reduce (Tail).
%% Functions can be polymorphic.
reduce () → reduce ([]).
20. Programming Erlang: the Sequential Part 20
Anonymous Functions (Funs)Anonymous Functions (Funs)
● A function is a first-order object.
● It can be anonymous (like a closure)—a fun.
● Funs can be passed as parameters.
● Funs can be returned.
22. Programming Erlang: the Sequential Part 22
Module “lists”Module “lists”
● Implicitly imported.
● lists:map/2 applies a function to a list and returns a new list
● lists:filter/2 returns a list of elements for which a function returns true
● lists:seq/2 returns a list of sequential integer numbers in a range
● lists:reverse/1 reverses a list (highly optimized!)
23. Programming Erlang: the Sequential Part 23
ExamplesExamples
1> lists:filter (fun (X) → X div 2 =:= X-1 end,
[1,2,3,4,5,6,7]).
[1,2]
2> lists:map (fun (X) → X*X end, [1,2,3,4,5,6,7]).
[1,4,9,16,25,36,49]
24. Programming Erlang: the Sequential Part 24
List ComprehensionList Comprehension
● List comprehensions are expression to create lists by rules
● A comprehension consists of a constructor and qualifiers (one or
more)
● A qualifier is a filter (a predicate or a boolean expression) or a
generator of the form Pattern←List
25. Programming Erlang: the Sequential Part 25
ExamplesExamples
1> [X*X || X←[1,2,3,4,5,6,7,8]].
[1,4,9,16,25,36,49,64]
2> [X*X || X←lists:seq (1,8)].
[1,4,9,16,25,36,49,64]
%% qsort
qsort ([])→[];
qsort ([Pivot|T]) → qsort ([X || X ← T, X < Pivot] ++
[Pivot] ++ qsort ([X || X←T, X >= Pivot]).
%% permutations
perms ([]) → [[]];
perms (L) → [[H|T] || H ← L, T ← perms (L--[H])].
26. Programming Erlang: the Sequential Part 26
Block ExpressionsBlock Expressions
● Used when more than one expression is needed to produce the value
(like progn in Lisp)
● The value of the block is the value of the last expression:
begin
expr1,
expr2,
expr3
end
27. Programming Erlang: the Sequential Part 27
GuardsGuards
● Guard sequence is a series of guards separated by “;” (meaning “or”)
● Guard is a sequence of guard expressions separated by “,” (meaning
“and”)
● Guard expression is true, constant (=false), guard predicate (is_atom,
is_number, etc.), guard built-in function (abs, float, etc.), term
comparison (/=,==,=/=,=:=,etc.), arithmetic expression or (short-
circuit) boolean expression
28. Programming Erlang: the Sequential Part 28
ExamplesExamples
small(X) when X=:=0 orelse 1/abs(X) > 1000 → true;
small(X) → false;
max(X,Y) when X>Y → X;
max(X,Y) when true → Y. %% when true is optional
… when is_tuple(X), size(X)=:=6, abs(element(3,X))>5
element(4,X)=:=hd(L) …
29. Programming Erlang: the Sequential Part 29
RecordsRecords
● Records are tuples with named elements.
● They are declared with -record() attribute.
● They are usually stored in *.hrl files.
● Those files are included with the -include(). attribute or
with rr() shell command
● Records are instantiated with the # operator with or without
default values
● Records can be copied with changes
● Fields can be extracted by matching
31. Programming Erlang: the Sequential Part 31
ExamplesExamples
clear_status (#todo{status=S,who=W})=R) →
R#todo{status=finished}.
32. Programming Erlang: the Sequential Part 32
Conditional statementsConditional statements
case Expression of
Pattern1 [when Guard1] → seq1;
Pattern2 [when Guard2] → seq2;
end
if
Guard1 → sequence1;
Guard2 → sequence2;
end
If there is no match, an exception is raised. Atom true matches everything.
33. Programming Erlang: the Sequential Part 33
ExamplesExamples
%% Split a lists into odd and even elements
odds_and_evens (L) →
odds_and_evens (L,[],[]).
odds_and_evens ([H|T],Odds,Evens) →
case (H rem 2) of
1 → odds_and_evens (T,[H|Odds],Evens);
0 → odds_and_evens (T, Odds, [H, Evens])
end
odds_and_evens ([], Odds, Evens) →
{lists:reverse (Odds), lists:reverse (Evens)}.
34. Programming Erlang: the Sequential Part 34
● There are three types of errors in Erlang:
● exit(Why) broadcasts {'EXIT',Pid,Why} to all linked processes
● throw(Why) throws an exception
● erlang:error(Why) terminates the current process immediately
Raising ExceptionsRaising Exceptions
35. Programming Erlang: the Sequential Part 35
Catching an ExceptionCatching an Exception
try FuncOrExprSeq
%% This part can be omitted
of
Pattern1 [when Guard1] → Expression1;
...
catch
%% Type can be throw (default), exit, error or _:_
ExType1: ExPattern1 [when ExGuard1] → ExExpr1;
...
after %% Guaranteed to execute!
AfterExpression
end
36. Programming Erlang: the Sequential Part 36
ExampleExample
try math:sqrt(-1)
catch
error: {badarith, _} → ....
end
37. Programming Erlang: the Sequential Part 37
Process DictionaryProcess Dictionary
● Each process has a private dictionary: an associative array
● Built-in functions (BIFs) to work with dictionaries:
● @spec put (Key, Value) → OldValue.
● @spec get (Key) → Value | undefined.
● @spec get_keys () → [Key].
● @spec get () → [{Key, Value}].
● @spec erase (Key) → Value.
● @spec erase() → [{Key, Value}].
38. Programming Erlang: the Sequential Part 38
MacrosMacros
● Defined using -define(). attribute.
● Called using ?.
● Parameters allowed.
● Predefined macros: ?FILE, ?MODULE, ?LINE.
● Other attributes: -ifdef()., -undef()., -ifndef()., -else., -endif.
39. Programming Erlang: the Sequential Part 39
ExamplesExamples
%% To be used in binaries
-define (DWORD, 32/unsigned-little-integer).
?DWORD.
%% Simple macro with parameters
-ifndef (isodd).
-define (isodd (X), X rem 2 =:= 1).
-endif.
?isodd (77).
40. Programming Erlang: the Sequential Part 40
This presentation roughly covers the first 27
pages (of the total of 29
) of
“Programming Erlang. Software for a Concurrent World,” by Joe
Armstrong.