<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mustafa on Medium]]></title>
        <description><![CDATA[Stories by Mustafa on Medium]]></description>
        <link>https://medium.com/@iqdeveloper?source=rss-b6fa7363ca32------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1LmUUbzIodEeW85t_5BMGA.jpeg</url>
            <title>Stories by Mustafa on Medium</title>
            <link>https://medium.com/@iqdeveloper?source=rss-b6fa7363ca32------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:19:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iqdeveloper/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Erlang?]]></title>
            <link>https://medium.com/@iqdeveloper/why-erlang-7ca6715286e6?source=rss-b6fa7363ca32------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ca6715286e6</guid>
            <category><![CDATA[schools]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mustafa]]></dc:creator>
            <pubDate>Mon, 22 Apr 2019 05:27:51 GMT</pubDate>
            <atom:updated>2019-04-22T23:42:11.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Benchmarking speed, safety, ease of use, memory footprint and Why to use it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*xQNvG3LdqJ_QV0P6vabPrw.png" /></figure><p>Now on the fifth and the last part of <strong>Erlang in 2019</strong> which you can read the first four parts from here</p><blockquote><a href="https://medium.com/@iqdeveloper/erlangcosc4-281c6db607a2">Part 1</a></blockquote><blockquote><a href="https://medium.com/@iqdeveloper/erlang-eb5b28d87453">Part 2</a></blockquote><blockquote><a href="https://medium.com/@iqdeveloper/debugging-in-erlang-9bbfee2af9c2">Part </a>3</blockquote><blockquote><a href="https://medium.com/@iqdeveloper/erlangtools-bd654272fea9">Part 4</a></blockquote><p>Moving now on an important part of any programming language, which is <strong><em>Benchmarking speed, safety, ease of use, memory footprint and Why to use it?</em></strong></p><h3><strong>1- Benchmarking speed</strong></h3><p>Benchmarking speed is used in programming as a way of testing out the performance of a certain program or algorithm. It is done in most languages by taking the time needed for execution, either measured in wall-clock or CPU time, of the program being tested. This test can give a general idea of the overall speed, but must always be taken with a grain of salt. There are a number of factors that can affect the speed of a program which don’t necessarily have to do with the program itself such as background tasks being run, the granularity of measurements, the heap size at the time of execution which can affect garbage collection and therefore performance, or even just the machine which the test is being run on. To retrieve the most relevant information from benchmarking speed, it is best to always perform the tests in the same environment, for as long a time as possible, and always in a newly created Erlang process.</p><p>Erlang provides a benchmark framework with two types of measurements, corresponding to wall-clock and CPU time respectively:</p><ul><li><strong>timer:tc/3</strong> for wall-clock time. This function will take the Module, Function, and Arguments as parameters and returns the elapsed time in microseconds and the return value of the function being tested. An example below shows the results of running this test three times on an arbitrary function:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*knpC-7VXljnFezNo" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*-93RSHGIhG88aDy9" /></figure><p>Measurements taken in wall-clock time take into account the time for things like I/O, swapping, and other activities in the OS kernel. However this can lead to a large variation in speed so it is best to run the test multiple times for best, worst, and average case conditions.</p><ul><li><strong>statictics/1 </strong>for CPU time. This function will take the argument runtime and return the total runtime and the time since the last call in milliseconds. To use this function to find the total time for a specific algorithm or function, call it immediately before and after the execution of the function and take the second returned value from the second call. In the example below I multiplied the time by 1000 to return it in microseconds like in the previous example:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/0*Pz7qRtk4-96-rYpD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*G2wAkzBi3myzssFY" /></figure><p>The first returned value from <strong>statistics(runtime)</strong> will return the sum of the runtime for all threads in the Erlang runtime system so for testing a specific function it can be more accurate to use the time since last call value.</p><h3><strong>2- Safety</strong></h3><blockquote><strong>Memory leak: </strong>From the general operating system perspective, some memory which is allocated but not used. From the Erlang perspective, Erlang is very poor and it always requests memory from the OS(it should be rich). If the allocated memory is not used properly by Erlang, we call it leaking the memory.</blockquote><p><strong>The allocation:</strong></p><p>When an application runs,it thrives to get enough RAM from the operating system. The erlang VM on which the application runs is equally responsible to give that memory back when not in use. This wouldn’t be the case every time especially when it is a large code base application and poorly maintained.</p><p><strong>Identifying a memory leak:</strong></p><p>When you start an application on the Erlang node, it usually consumes some <strong>“x MB”</strong> of RAM from the OS. You can see the RAM consumption using <strong>“top”</strong>command as below.</p><blockquote>top -p &lt;beam PID&gt;</blockquote><p>RSS field gives the resident memory size which is the minimum RAM consumption and Virt field gives the current runtime RAM consumption.</p><p>If you keep a note of these values before and after your use-case execution. It should almost be the same. You can expect a slight increase in these values as your use-case might add some values into ETS or Mnesia(ram_copies) which most likely be stored in RAM and may slightly increase the consumption.</p><p><strong>The analysis:</strong></p><p>Now if you see much difference(In my case &gt;20MB) in the RAM utilization even after the use-case is completed. Our adventure begins here:</p><p>Take snapshots of following command <strong><em>erlang:memory() </em></strong>before and after the use-case.</p><blockquote><strong>erlang:memory() </strong>function gives you memory utilization in bytes segregated datatype wise like ets,atom,binary,proc_memory etc., Each and every datatype should be checked whether it is increased after the use-case. Something’s you can straight away suspect are ETS,binary,atom_table and process memory.</blockquote><p><strong>Some functions that might help:</strong></p><blockquote>To find all process memory, use below:</blockquote><blockquote>[io:format(“~p:~p: ~p~n”,[Pid,erlang:process_info(Pid,current_function),erlang:process_info(Pid,memory)])||Pid&lt;-erlang:processes()].</blockquote><blockquote>To find all ets tables memory and entries, use below:</blockquote><blockquote>[io:format(“~p -&gt; ~p: ~p mem ~p ~n”,[E,ets:info(E,name),ets:info(E,size),ets:info(E,memory)])||E&lt;-ets:all()],calendar:local_time().</blockquote><blockquote>Sometimes you may need to find the message_queue_len, use below:</blockquote><blockquote>[io:format(“~p:~p: Q:~p ~p~n”,[Pid,erlang:process_info(Pid,current_function),erlang:process_info(Pid,message_queue_len),erlang:process_info(Pid,memory)])||Pid&lt;-erlang:processes()].</blockquote><p>We can also add some sorting function to sort the outcome of above results. But I am not a keep it clean type, I always love skimming through the whole outcome in search of more clues.</p><p>In the above cases, if you keenly observe, I tried to print the current function of every process together with memory. This current_function will mostly likely be the honeypot of the high memory consuming process from which you can start your investigation. I can easily assure you that such memory leak cases can most likely be lingering around that function.</p><blockquote>The quick work-around:</blockquote><blockquote>Adding a <strong>erlang:garbage_collect(self())</strong> to the code where you have found/suspect the memory leak would be a quickest way to check/cure memory leak.</blockquote><blockquote>But this is really not a good fix. Using garbage_collect more frequently eats up CPU. Instead, We should try to fix the code.</blockquote><h3><strong>3- Ease of Use</strong></h3><p>There are many benefits to using Erlang, one major one is the ease of use. Erlang is a stable language that within major systems can run core procedures.</p><p>Error handling is an aspect which is handled much easier than in other languages. Error recovery and handling of concurrency use an Actor system to simplify them. The basics of the Actor system is you can send messages to an actor, or receive a message from an actor, but you can’t access it’s internal logic directly. This allows making it able to use multicore computing to make handling more jobs with less work and thus makes it beneficial in terms of time and work.</p><p>This language is relatively easy to learn in comparison with other programming languages. In Erlang, there are single assignments of variables, no objects, and recognition of everything as a function. These make coding in erlang much shorter and expressive, thus quicker and easier to use. Recursion and pattern matching make conditionals much easier to handle as well and does not leave dangling. Overall, these benefits make learning and advancing in programming easier and beneficial to beginners and advanced programmers.</p><h3><strong>4- Memory Footprint</strong></h3><p>When you start an application on the Erlang node, it usually consumes some “x MB” of RAM from the OS. You can see the RAM consumption using “top” command as below. RSS field gives the resident memory size which is the minimum RAM consumption and Virt field gives the current runtime RAM consumption.</p><p>A good start when programming efficiently is to know how much memory different data types and operations require. It is implementation-dependent how much memory the Erlang data types and other items consume, but the following table shows some figures for the erts-8.0 system in OTP 19.0.</p><p>The unit of measurement is memory words. There exists both a 32-bit and a 64-bit implementation. A word is therefore 4 bytes or 8 bytes, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SkgrQJrXMSDY3x60QuTaw.png" /></figure><p>The Erlang language specification puts no limits on the number of processes, length of atoms, and so on. However, for performance and memory saving reasons, there will always be limits in a practical implementation of the Erlang language and execution environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9BGMTC9nK9ag2Hl0-3pPA.png" /></figure><h3>5- Why to use it?</h3><blockquote>srouce: <a href="http://erlang.org/faq/introduction.html">http://erlang.org/faq/introduction.html</a></blockquote><p>Erlang is a functional language as well as a stable and trusted language. Erlang has a built-in support for distribution, fault tolerance and concurrency. it also used in several large telecommunication system from Ericsson.</p><p>Erlang is a general-Purpose programming language and runtime environment designed for highly parallel, scalable application requiring high uptime “The original use case, and still the primary one, is to program Ericsson cellular data carrier nodes (hence “Er”-lang), which carry about 40% of global cell phone traffic. The original spec was “nine nines” uptime (99.9999999% uptime; that is 31.536 <em>milliseconds</em> allowable downtime per year)”.In Erlang functional language errors or code updates do not require to stop or restart the entire process in order to recover, and that what make the language more sufficient and easier to use. We also can also make web apps, multi users systems accounting using erlang, Erlang made for Multi use systems. Erlang provides a powerful and simple model for error containment. Erlang also known as a software architect which make the language very valuable.</p><p><strong>What sort of applications is Erlang particularly suitable for?</strong></p><ul><li>Telecommunication systems, e.g. controlling a switch or converting protocols.</li><li>Servers for Internet applications, e.g. a mail transfer agent, an IMAP-4 server, an HTTP server or a <a href="http://www.erlang.se/euc/99/WAP/index.htm"><strong>WAP Stack</strong></a>.</li><li>Telecommunication applications, e.g. handling mobility in a mobile network or providing unified messaging.</li><li>Database applications which require soft realtime behavior.</li><li>Erlang is good at solving these sorts of problems because this is the problem domain it was originally designed for. Stating the above in terms of features:</li><li>Erlang provides a simple and powerful model for error containment and fault tolerance (supervised processes).</li><li>Concurrency and message passing are a fundamental to the language. Applications written in Erlang are often composed of hundreds or thousands of lightweight processes. Context switching between Erlang processes is typically one or two orders of magnitude cheaper than switching between threads in a C program.</li><li>Writing applications which are made of parts which execute on different machines (i.e. distributed applications) is easy. Erlang’s distribution mechanisms are transparent: programs need not be aware that they are distributed.</li><li>The OTP libraries provide support for many common problems in networking and telecommunications systems.</li><li>The Erlang runtime environment (a virtual machine, much like the Java virtual machine) means that code compiled on one architecture runs anywhere. The runtime system also allows code in a running system to be updated without interrupting the program.</li></ul><p><strong>Authors: </strong>Group 10</p><ul><li><a href="http://mustafallica.github.io/">MUSTAFA AL-JABURI</a></li><li><a href="http://www.linkedin.com/in/jillianfredette/">JILLIAN FREDETTE</a></li><li><a href="https://www.linkedin.com/in/sylvia-palos-a16361180">SYLVIA PALOS</a></li><li><a href="https://www.linkedin.com/in/gbaban/">GHADA BABAN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ca6715286e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Erlang Toolchains and Intermediate representations]]></title>
            <link>https://medium.com/@iqdeveloper/erlangtools-bd654272fea9?source=rss-b6fa7363ca32------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd654272fea9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[erlang]]></category>
            <dc:creator><![CDATA[Mustafa]]></dc:creator>
            <pubDate>Mon, 01 Apr 2019 02:31:57 GMT</pubDate>
            <atom:updated>2019-04-01T02:31:57.987Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>a brief summary of Erlang’s Intermediate representations, Toolchain and internals</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*xQNvG3LdqJ_QV0P6vabPrw.png" /></figure><p>Now on the fourth part of <strong>Erlang in 2019</strong> which you can read the first three parts from here</p><blockquote><a href="https://medium.com/@iqdeveloper/erlangcosc4-281c6db607a2">Part 1</a></blockquote><blockquote><a href="https://medium.com/@iqdeveloper/erlang-eb5b28d87453">Part 2</a></blockquote><blockquote><a href="https://medium.com/@iqdeveloper/debugging-in-erlang-9bbfee2af9c2">Part 3</a></blockquote><p>Moving now on an important part of any programming language, which is <strong>Erlang’s Intermediate representations, Toolchain and internals.</strong></p><p>Erlang has a very robust development chain, especially if you are an EMACS maven. There is an Erlang specific build system, there is robust support for packaging your application and its dependencies for deployment and don’t forget OTP.</p><p>As for tools, there is Dialyzer, real time tracing on running systems, hot code loading ( you can enable and disable or add logging to a running system without restarting it, for example ), remote code execution, there is so much to learn it is dizzying when you start out.</p><ul><li>Editor: you can use whatever you want. I used emacs for my first year of erlang, but I’m currently using gedit.</li><li>Version Control: I like git. It seems that most of the erlang community agrees (most projects are hosted on github).</li><li>Workflow: I’d recommend getting familiar with <a href="https://github.com/basho/rebar">rebar</a>.</li></ul><p>Here is an example of a rebar-flavored Makefile:</p><pre>REBAR := ./rebar</pre><pre>.PHONY: all deps doc test clean release</pre><pre>all: deps<br>    $(REBAR) compile</pre><pre>deps:<br>    $(REBAR) get-deps</pre><pre>doc:<br>    $(REBAR) doc skip_deps=true</pre><pre>test:<br>    $(REBAR) eunit skip_deps=true</pre><pre>clean:<br>    $(REBAR) clean</pre><pre>release: all test<br>    dialyzer --src src/*.erl deps/*/src/*.erl</pre><p>Here are some basic pointers:</p><ul><li>Put your unit tests in the same modules as the code they are testing. See the rebar wiki for details.</li><li>Add {cover_enabled, true} to your rebar.config file. Every time you run make test you get a coverage report in HTML!</li><li>Add your project’s dependencies to your rebar.config and you can fetch and build them when you run make deps.</li><li>Make sure to comment your code with edoc. If you do, rebar can build all of your docs when your run make doc.</li></ul><h3>Setting up Dependencies</h3><p>The basic configuration of a project should do at least two things:</p><ol><li>Always track the rebar.lock file</li><li>Ignore the _build directory</li></ol><p>Tracking the lock file will let you have repeatable builds, and will allow rebar3 to do things like automatically re-update dependencies when switching branches.</p><h3>The _build directory should be safe to delete but you shouldn’t need to</h3><p>Rebar3 tracks all the applications declared in your rebar.config files and should be able to track all required changes.</p><p>There are a few edge cases where this is not possible and may lead to weird bugs, specifically when you are changing your project structure. If you are moving from a single-app project to an umbrella project (i.e. all source files move from src/ to apps/myapp/src) or the opposite, there are chances that various artifacts in the _build directory will conflict with each other. Delete it and ask for a fresh build in this case.</p><p>The next thing you’ll want to do is add dependencies to your project. See the <a href="https://www.rebar3.org/docs/dependencies">Dependencies</a>section for this. Adding dependencies does not automatically integrate them to your project, however.</p><p>The {deps, [...]} configuration value tells rebar3 which dependencies to fetch and download and track, but that&#39;s as far as it goes. You must then configure your application to make use of the dependency:</p><ul><li>If the dependency is needed at runtime by your application in order for it to work (e.g. you need a web server or call the library directly), add it to your application’s .app.src file under the {applications, [stdlib, kernel, ...]} tuple. This will let the Erlang VM know not to boot your app without the dependency being present</li><li>If the dependency is only needed for releases (for example, observer or recon, which are debugging tools that your application likely does not depend on but you&#39;d like to bundle it), then you need to app that application explicitly to the {releases, ...} configuration tuple. Any dependency in that tuple will have its transitive dependencies included as well.</li></ul><p>Other build tools tend to make no distinction between these types of project inclusions, but rebar3 tries to be strict with regards to what should be included or not. It can let you make specific builds, such as escripts or test releases that won’t require specific toolchains like the Wx graphical toolkit in order to run.</p><blockquote><a href="https://github.com/grisp/grisp-software#prerequisites">GRISP Toolchain</a></blockquote><h3>Intermediate representations</h3><h4>Records</h4><p>Records are, first of all, a hack. They are more or less an afterthought to the language and can have their share of inconveniences. I’ll cover that later. They’re still pretty useful whenever you have a small data structure where you want to access the attributes by name directly. As such, Erlang records are a lot like structs in C (if you know C.)</p><p>They’re declared as module attributes in the following manner:</p><pre>-module(records).<br>-compile(export_all).</pre><pre>-record(robot, {name,<br>                type=industrial,<br>                hobbies,<br>                details=[]}).</pre><p>So here we have a record representing robots with 4 fields: name, type, hobbies and details. There is also a default value for type and details, industrial and [], respectively. Here&#39;s how to declare a record in the module <a href="https://learnyousomeerlang.com/static/erlang/records.erl">records</a>:</p><pre>first_robot() -&gt;<br>    #robot{name=&quot;Mechatron&quot;,<br>           type=handmade, <br>           details=[&quot;Moved by a small man inside&quot;]}.</pre><p>And running the code:</p><pre>1&gt; c(records).<br>{ok,records}<br>2&gt; records:first_robot().<br>{robot,&quot;Mechatron&quot;,handmade,undefined,<br>       [&quot;Moved by a small man inside&quot;]}</pre><p>Woops! Here comes the hack! Erlang records are just syntactic sugar on top of tuples. Fortunately, there’s a way to make it better. The Erlang shell has a command rr(Module) that lets you load record definitions from Module:</p><pre>3&gt; rr(records).<br>[robot]<br>4&gt; records:first_robot().         <br>#robot{name = &quot;Mechatron&quot;,type = handmade,<br>       hobbies = undefined,<br>       details = [&quot;Moved by a small man inside&quot;]}</pre><p>Ah there! This makes it much easier to work with records that way. You’ll notice that in first_robot/0, we had not defined the hobbies field and it had no default value in its declaration. Erlang, by defaults, sets the value to undefined for you.</p><p>To see the behavior of the defaults we set in the robot definition, let&#39;s compile the following function:</p><pre>car_factory(CorpName) -&gt;<br>    #robot{name=CorpName, hobbies=&quot;building cars&quot;}.</pre><p>And run it:</p><pre>5&gt; c(records).<br>{ok,records}<br>6&gt; records:car_factory(&quot;Jokeswagen&quot;).<br>#robot{name = &quot;Jokeswagen&quot;,type = industrial,<br>       hobbies = &quot;building cars&quot;,details = []}</pre><p>And we have an industrial robot that likes to spend time building cars.</p><p><strong>Note:</strong> The function rr() can take more than a module name: it can take a wildcard (like rr(&quot;*&quot;)) and also a list as a second argument to specify which records to load.</p><p>There are a few other functions to deal with records in the shell: rd(Name, Definition) lets you define a record in a manner similar to the -record(Name, Definition) used in our module. You can use rf() to &#39;unload&#39; all records, or rf(Name) or rf([Names]) to get rid of specific definitions.</p><p>You can use rl() to print all record definitions in a way you could copy-paste into the module or use rl(Name) or rl([Names]) to restrict it to specific records.</p><p>Finally, rp(Term) lets you convert a tuple to a record (given the definition exists)</p><p>Writing records alone won’t do much. We need a way to extract values from them. There are basically two ways to do this. The first one is with a special ‘dot syntax’. Assuming you have the record definition for robots loaded:</p><pre>5&gt; Crusher = #robot{name=&quot;Crusher&quot;, hobbies=[&quot;Crushing people&quot;,&quot;petting cats&quot;]}. <br>#robot{name = &quot;Crusher&quot;,type = industrial,<br>       hobbies = [&quot;Crushing people&quot;,&quot;petting cats&quot;],<br>       details = []}<br>6&gt; Crusher#robot.hobbies.<br>[&quot;Crushing people&quot;,&quot;petting cats&quot;]</pre><p>Ugh, not a pretty syntax. This is due to the nature of records as tuples. Because they’re just some kind of compiler trick, you have to keep keywords around defining what record goes with what variable, hence the #robot part of Crusher#robot.hobbies. It&#39;s sad, but there&#39;s no way out of it. Worse than that, nested records get pretty ugly:</p><pre>7&gt; NestedBot = #robot{details=#robot{name=&quot;erNest&quot;}}.<br>#robot{name = undefined,type = industrial,<br>       hobbies = undefined,<br>       details = #robot{name = &quot;erNest&quot;,type = industrial,<br>                        hobbies = undefined,details = []}}<br>8&gt; (NestedBot#robot.details)#robot.name. <br>&quot;erNest&quot;</pre><p>And yes, the parentheses are mandatory.</p><p><strong>Update:</strong><br>Starting with revision R14A, it is now possible to nest records without the parentheses. The NestedBot example above could also be written as NestedRobot#robot.details#robot.name and work the same.</p><p>To further show the dependence of records on tuples, see the following:</p><pre>9&gt; #robot.type.<br>3</pre><p>What this outputs is which element of the underlying tuple it is.</p><p>One saving feature of records is the possibility to use them in function heads to pattern match and also in guards. Declare a new record as follows on top of the file, and then add the functions under:</p><pre>-record(user, {id, name, group, age}).</pre><pre>%% use pattern matching to filter<br>admin_panel(#user{name=Name, group=admin}) -&gt;<br>    Name ++ &quot; is allowed!&quot;;<br>admin_panel(#user{name=Name}) -&gt;<br>    Name ++ &quot; is not allowed&quot;.</pre><pre>%% can extend user without problem<br>adult_section(U = #user{}) when U#user.age &gt;= 18 -&gt;<br>    %% Show stuff that can&#39;t be written in such a text<br>    allowed;<br>adult_section(_) -&gt;<br>    %% redirect to sesame street site<br>    forbidden.</pre><p>The syntax to bind a variable to any field of a record is demonstrated in the admin_panel/1 function (it&#39;s possible to bind variables to more than one field). An important thing to note about the adult_section/1 function is that you need to do SomeVar = #some_record{} in order to bind the whole record to a variable. Then we do the compiling as usual:</p><pre>10&gt; c(records).<br>{ok,records}<br>11&gt; rr(records).<br>[robot,user]<br>12&gt; records:admin_panel(#user{id=1, name=&quot;ferd&quot;, group=admin, age=96}).<br>&quot;ferd is allowed!&quot;<br>13&gt; records:admin_panel(#user{id=2, name=&quot;you&quot;, group=users, age=66}). <br>&quot;you is not allowed&quot;<br>14&gt; records:adult_section(#user{id=21, name=&quot;Bill&quot;, group=users, age=72}).<br>allowed<br>15&gt; records:adult_section(#user{id=22, name=&quot;Noah&quot;, group=users, age=13}).<br>forbidden</pre><p>What this lets us see is how it is not necessary to match on all parts of the tuple or even know how many there are when writing the function: we can only match on the age or the group if that’s what’s needed and forget about all the rest of the structure. If we were to use a normal tuple, the function definition might need to look a bit like function({record, _, _, ICareAboutThis, _, _}) -&gt; .... Then, whenever someone decides to add an element to the tuple, someone else (probably angry about it all) would need to go around and update all functions where that tuple is used.</p><h4>Key-Value Stores</h4><p>I’ve had you build a tree back a few chapters, and the use was to use it as a key-value store for an address book. That book sucked: we couldn’t delete or convert it to anything useful. It was a good demonstration of recursion, but not much more. Now is the time to introduce you to a bunch of useful data structures and modules to store data under a certain key. I won’t define what every function does nor go through all the modules. I will simply link to the doc pages. Consider me as someone responsible about ‘raising awareness about key-value stores in Erlang’ or something. Sounds like a good title. I just need one of these ribbons.</p><p>For small amounts of data, there are basically two data structures that can be used. The first one is called a <em>proplist</em>. A proplist is any list of tuples of the form [{Key,Value}]. They&#39;re a weird kind of structure because there is no other rule than that. In fact the rules are so relaxed that the list can also contain boolean values, integers and whatever you want. We&#39;re rather interested by the idea of a tuple with a key and a value in a list here, though. To work with proplists, you can use the <a href="http://erldocs.com/18.0/stdlib/proplists.html">proplists</a> module. It contains functions such as <a href="http://erldocs.com/18.0/stdlib/proplists.html#delete/2">proplists:delete/2</a>, <a href="http://erldocs.com/18.0/stdlib/proplists.html#get_value/2">proplists:get_value/2</a>, <a href="http://erldocs.com/18.0/stdlib/proplists.html#get_all_values/2">proplists:get_all_values/2</a>, <a href="http://erldocs.com/18.0/stdlib/proplists.html#lookup/2">proplists:lookup/2</a> and <a href="http://erldocs.com/18.0/stdlib/proplists.html#lookup_all/2">proplists:lookup_all/2</a>.</p><p>You’ll notice there is no function to add or update an element of the list. This shows how loosely defined proplists are as a data structure. To get these functionalities, you must cons your element manually ([NewElement|OldList]) and use functions such as <a href="http://erldocs.com/18.0/stdlib/lists.html#keyreplace/4">lists:keyreplace/4</a>. Using two modules for one small data structure is not the cleanest thing, but because proplists are so loosely defined, they&#39;re often used to deal with configuration lists, and general description of a given item. Proplists are not exactly complete data structures. They&#39;re more of a common pattern that appears when using lists and tuples to represent some object or item; the proplists module is a bit of a toolbox over such a pattern.</p><p>If you do want a more complete key-value store for small amounts of data, the <a href="http://erldocs.com/18.0/stdlib/orddict.html">orddict</a> module is what you need. Orddicts (ordered dictionaries) are proplists with a taste for formality. Each key can be there once, the whole list is sorted for faster average lookup, etc. Common functions for the CRUD usage include <a href="http://erldocs.com/18.0/stdlib/orddict.html#store/3">orddict:store/3</a>, <a href="http://erldocs.com/18.0/stdlib/orddict.html#find/2">orddict:find/2</a> (when you do not know whether the key is in the dictionaries), <a href="http://erldocs.com/18.0/stdlib/orddict.html#fetch/2">orddict:fetch/2</a> (when you know it is there or that it <strong>must</strong> be there) and <a href="http://erldocs.com/18.0/stdlib/orddict.html#erase/2">orddict:erase/2</a>.</p><p>I would therefore say that your application’s needs is what should govern which key-value store to choose. Different factors such as how much data you’ve got to store, what you need to do with it and whatnot all have their importance. Measure, profile and benchmark to make sure.</p><h4>Arrays</h4><p>But what about code that requires data structures with nothing but numeric keys? Well for that, there are <a href="http://erldocs.com/18.0/stdlib/array.html">arrays</a>. They allow you to access elements with numerical indices and to fold over the whole structure while possibly ignoring undefined slots.</p><h4>A Set of Sets</h4><p>If you’ve ever studied set theory in whatever mathematics class you have an idea about what sets can do. If you haven’t, you might want to skip over this. However, I’ll just say that sets are groups of unique elements that you can compare and operate on: find which elements are in two groups, in none of them, only in one or the other, etc. There are more advanced operations letting you define relations and operate on these relations and much more. I’m not going to dive into the theory (again, it’s out of the scope of this book) so I’ll just describe them as it is.</p><p>There are 4 main modules to deal with sets in Erlang. This is a bit weird at first, but it makes more sense once you realize that it’s because it was agreed by implementers that there was no ‘best’ way to build a set. The four modules are <a href="http://erldocs.com/18.0/stdlib/ordsets.html">ordsets</a>, <a href="http://erldocs.com/18.0/stdlib/sets.html">sets</a>, <a href="http://erldocs.com/18.0/stdlib/gb_sets.html">gb_sets</a> and <a href="http://erldocs.com/18.0/stdlib/sofs.html">sofs</a> (sets of sets):</p><p><strong>ordsetsOrdsets</strong> are implemented as a sorted list. They’re mainly useful for small sets, are the slowest kind of set, but they have the simplest and most readable representation of all sets. There are standard functions for them such as <a href="http://erldocs.com/18.0/stdlib/ordsets.html#new/0">ordsets:new/0</a>, <a href="http://erldocs.com/18.0/stdlib/ordsets.html#is_element/2">ordsets:is_element/2</a>, <a href="http://erldocs.com/18.0/stdlib/ordsets.html#add_element/2">ordsets:add_element/2</a>, <a href="http://erldocs.com/18.0/stdlib/ordsets.html#del_element/2">ordsets:del_element/2</a>, <a href="http://erldocs.com/18.0/stdlib/ordsets.html#union/1">ordsets:union/1</a>, <a href="http://erldocs.com/18.0/stdlib/ordsets.html#intersection/1">ordsets:intersection/1</a>, and a bunch more.</p><p><strong>sets</strong> Sets (the module) is implemented on top of a structure really similar to the one used in dict. They implement the same interface as ordsets, but they&#39;re going to scale much better. Like dictionaries, they&#39;re especially good for read-intensive manipulations, like checking whether some element is part of the set or not.</p><p><strong>gb_sets</strong> Gb_sets themselves are constructed above a General Balanced Tree structure similar to the one used in the gb_trees module. gb_sets are to sets what gb_tree is to dict; an implementation that is faster when considering operations different than reading, leaving you with more control. While gb_sets implement the same interface as sets and ordsets, they also add more functions. Like gb_trees, you have smart vs. naive functions, iterators, quick access to the smallest and largest values, etc.</p><p><strong>sofs</strong> Sets of sets (sofs) are implemented with sorted lists, stuck inside a tuple with some metadata. They’re the module to use if you want to have full control over relationships between sets, families, enforce set types, etc. They’re really what you want if you need mathematics concept rather than ‘just’ groups of unique elements.</p><h4>Directed Graphs</h4><p>There is one other data structure that I want to mention here (not that there are not more than what’s mentioned in this chapter, on the contrary): <a href="http://en.wikipedia.org/wiki/Directed_graph">directed graphs</a>. Again, this data structure is more for readers who already know the mathematical theory that goes with it.</p><p>Directed graphs in Erlang are implemented as two modules, <a href="http://erldocs.com/18.0/stdlib/digraph.html">digraph</a> and <a href="http://erldocs.com/18.0/stdlib/digraph_utils">digraph_utils</a>. The digraph module basically allows the construction and modification of a directed graph: manipulating edges and vertices, finding paths and cycles, etc. On the other hand, digraph_utils allows you to navigate a graph (postorder, preorder), testing for cycles, arborescences or trees, finding neighbors, and so on.</p><p>Because directed graphs are closely related to set theory, the ‘sofs’ module contains a few functions letting you convert <a href="http://erldocs.com/18.0/stdlib/sofs.html#family_to_digraph/2">families to digraphs</a> and <a href="http://erldocs.com/18.0/stdlib/sofs.html#digraph_to_family/2">digraphs to families</a>.</p><h4>Queues</h4><p>The <a href="http://erldocs.com/18.0/stdlib/queue.html">queue module</a> implements a double-ended FIFO (<a href="http://en.wikipedia.org/wiki/FIFO_(computing)">First In, First Out</a>) queue:</p><p>They’re implemented a bit as illustrated above: two lists (in this context, stacks) that allow to both append and prepend elements rapidly.</p><p>The queue module basically has different functions in a mental separation into 3 interfaces (or APIs) of varying complexity, called ‘Original API’, ‘Extended API’ and ‘Okasaki API’:</p><ul><li>The original API contains the functions at the base of the queue concept, including: <a href="http://erldocs.com/18.0/stdlib/queue.html#new/0">new/0</a>, for creating empty queues, <a href="http://erldocs.com/18.0/stdlib/queue.html#in/2">in/2</a>, for inserting new elements, <a href="http://erldocs.com/18.0/stdlib/queue.html#out/1">out/1</a>, for removing elements, and then functions to convert to lists, reverse the queue, look if a particular value is part of it, etc.</li><li>The extended API mainly adds some introspection power and flexibility: it lets you do things such as looking at the front of the queue without removing the first element (see <a href="http://erldocs.com/18.0/stdlib/queue.html#get/1">get/1</a> or <a href="http://erldocs.com/18.0/stdlib/queue.html#peek/1">peek/1</a>), removing elements without caring about them (<a href="http://erldocs.com/18.0/stdlib/queue.html#drop/1">drop/1</a>), etc. These functions are not essential to the concept of queues, but they&#39;re still useful in general.</li><li>The Okasaki API is a bit weird. It’s derived from Chris Okasaki’s <a href="http://books.google.ca/books?id=SxPzSTcTalAC&amp;lpg=PP1&amp;dq=chris%20okasaki%20purely%20functional%20data%20structures&amp;pg=PP1#v=onepage&amp;q=&amp;f=false"><em>Purely Functional Data Structures</em></a>. The API provides operations similar to what was available in the two previous APIs, but some of the function names are written backwards and the whole thing is relatively peculiar. Unless you do know you want this API, I wouldn’t bother with it.</li></ul><p>You’ll generally want to use queues when you’ll need to ensure that the first item ordered is indeed the first one processed. So far, the examples I’ve shown mainly used lists as a accumulators that would then be reversed. In cases where you can’t just do all the reversing at once and elements are frequently added, the queue module is what you want (well, you should test and measure first! Always test and measure first!)</p><p><strong>Authors: </strong>Group 10</p><ul><li><a href="http://mustafallica.github.io/">MUSTAFA AL-JABURI</a></li><li><a href="http://www.linkedin.com/in/jillianfredette/">JILLIAN FREDETTE</a></li><li><a href="https://www.linkedin.com/in/sylvia-palos-a16361180">SYLVIA PALOS</a></li><li><a href="https://www.linkedin.com/in/gbaban/">GHADA BABAN</a></li><li><a href="http://linkedin.com/in/adan-ramirez-525330146">ADAN RAMIREZ</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd654272fea9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging in Erlang]]></title>
            <link>https://medium.com/@iqdeveloper/debugging-in-erlang-9bbfee2af9c2?source=rss-b6fa7363ca32------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bbfee2af9c2</guid>
            <category><![CDATA[erlang]]></category>
            <dc:creator><![CDATA[Mustafa]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 03:08:07 GMT</pubDate>
            <atom:updated>2019-03-20T05:32:08.978Z</atom:updated>
            <content:encoded><![CDATA[<p>An inside look on how to perform debugging in Erlang.</p><p>Now on the third part of <strong>Erlang in 2019</strong> which you can read the first two parts from here</p><blockquote><a href="https://medium.com/@iqdeveloper/erlangcosc4-281c6db607a2">Part 1</a></blockquote><blockquote><a href="https://medium.com/@iqdeveloper/erlang-eb5b28d87453">Part 2</a></blockquote><p>Moving now on an important part of any programming language, which is <strong>DEBUGGING</strong></p><h3>1 — Debugging and testing support</h3><p>Now that we are familiar with erlang and able to create a module, we can start looking into erlangs debugger. The monitor window will display when you call,</p><blockquote><em>debugger:start().</em></blockquote><p>In the erlang terminal. Then select</p><blockquote>Module &gt; Interpret… and select the appropriate module.</blockquote><p>To view the contents of the source file you select</p><blockquote>Module &gt; module to be interpreted &gt; View</blockquote><p>Now you can set breakpoints in the source code. The breakpoints can only be set at an executable line. A blank line, line containing comment, function head, or pattern in a case or receive statement is not executable. The trigger action allows you to enable, disable, or delete breakpoints. You can set a line break, conditional break, or a function break.</p><p>Line Breakpoint:</p><p>A line break can be set by selecting,</p><blockquote>Break &gt; Line Break…</blockquote><p>A popup menu will appear allowing you to select the module, enter the breakpoint line number, and selecting the trigger action.</p><p>Conditional Breakpoint:</p><p>A conditonal breakpoint can be set by selecting,</p><blockquote>Break &gt; Conditional Break…</blockquote><p>A popup menu will appear allowing you to select the module, breakpoint line number, specifying the CModule and CFunction, and trigger action. The condition is specified as a module name CModule and function name CFunction. When the process reaches the breakpoint, CModule:CFunction(Binding) is evaluated. If the function returns true the process stops and if the function returns false the breakpoint is ignored. Binding is a list of variable bindings and the variable can be retrieved by using the fuction int:get_binding(Variable, Bindings).</p><p>Function Breakpoint:</p><p>To set a function breakpoint select,</p><blockquote>Break &gt; Function Break…</blockquote><p>The popup menu will appear allowing you select the module and function. A function breakpoint is a set of line breakpoints, one at the first line of the specified function.</p><h3>2 — Demonstration of debugger</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FgUY9whzWG_s%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DgUY9whzWG_s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FgUY9whzWG_s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/73a7c375a8fc4ce322bc990bdcc76595/href">https://medium.com/media/73a7c375a8fc4ce322bc990bdcc76595/href</a></iframe><h3>3 — Unit testing framework</h3><p><strong>EUnit — a Lightweight Unit Testing Framework for Erlang</strong></p><p>Being able to test small portions or ‘units’ of your program is extremely useful in optimizing your code, and the time you spend writing it. EUnit is the Erlang specific unit testing framework which builds on other object-oriented language unit testing frameworks. We will give you an introduction to EUnit and some examples of its use.</p><p>Getting Started with EUnit:</p><p>To use EUnit in your module, simply add the header</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*N5joi1vw5YiBKdShp1UbNA.png" /></figure><p>in your module directly after its declaration. This will create an exported function test(), cause all functions whose names match …_test()(test function) or …_test_() (test generator function) to be automatically exported from the module, and makes all the preprocessor macros of EUnit available to help in writing tests.</p><p><strong>Writing Test Functions:</strong></p><p>A simple test function recognized by EUnit is anyone with a name ending in …_test() which takes no arguments and when executed it will either succeed or throw an exception. And example of what this code might look like would be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*Um77BfZSuqdytdcpHY3rJA.png" /></figure><p>Which one might use test that the function function_to_test() does not crash when given the input function_input.</p><p>We can write more complicated tests which will do more than simply show us that a function won’t crash. We can use pattern match to throw a ‘badmatch’ error, an example of this would be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*-_Ygo1ptwyjhEZgMkuy5Og.png" /></figure><p>This updated example will cause the program to crash and thrown an exception if function_to_test(function_input) does not return []. This is extremely useful if you know the expected output of the function you are testing for the specified input.</p><p>We can also go a step further and use Boolean operators by using the assert macro. An example of this is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*52rT176cO-bQd47FDwPTvA.png" /></figure><p>This will also test that the function will return a certain expected value and assert will either return ok if the test evaluates to true or throw an exception if it does not give the expected return value.</p><p><strong>Running EUnit</strong></p><p>All you need to do to run the tests you’ve defined on your module which includes the EUnit header is to compile the module, and then run</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*43Me3B4Ny-zryAaribIjXg.png" /></figure><p>Which will run all tests defined in your module.</p><p><strong>Test Generating Functions</strong></p><p>Test generating functions in EUnit return a representation of a set of tests to be executed, this allows you to bypass the need for writing separate test functions with separate names for each test case. EUnit will put all the tests generated by this function into a list and run them one-by-one. Test generated functions have a name ending with …_test_() and adding an underscore in front of the macro which will be used for the test will signal that that macro is a test object. An example of this is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*WYl9GI7TSaMxlb5lB8xUCA.png" /></figure><p>Which when run will test that each of these three inputs to the function to be tested will have the same expected output. Not the underscore in front of the assert macro which signals that this is a test object.</p><blockquote>source: <em>: </em><a href="http://erlang.org/doc/apps/eunit/chapter.html"><em>http://erlang.org/doc/apps/eunit/chapter.html</em></a></blockquote><p><strong>Common Test Basics</strong></p><p>The Common Test framework is a tool that supports implementation and automated execution of test cases to any types of target systems. Common Test is the main tool being used in all testing- and verification activities that are part of Erlang/OTP system development and maintenance.</p><ul><li><strong>Common Test</strong> is also a very useful tool for white-box testing Erlang code for example<strong> (module testing)</strong>, as the test programs can call exported Erlang functions directly</li></ul><blockquote><em>The Common Test server requires that the test suite defines and exports the following mandatory or optional callback functions:</em></blockquote><ul><li><strong>all(): </strong>Returns a list of all test cases and groups in the suite. (Mandatory)</li><li><strong>suite(): </strong>Information function used to return properties for the suite. (Optional)</li><li><strong>groups(): </strong>For declaring test case groups. (Optional)</li><li><strong>init_per_suite(Config): </strong>Suite level configuration function, executed before the first test case. (Optional)</li><li><strong>end_per_suite(Config): </strong>Suite level configuration function, executed after the last test case. (Optional)</li><li><strong>group(GroupName): </strong>Information function used to return properties for a test case group. (Optional)</li><li><strong>init_per_group(GroupName, Config): </strong>Configuration function for a group, executed before the first test case. (Optional)</li><li><strong>end_per_group(GroupName, Config): </strong>Configuration function for a group, executed after the last test case. (Optional)</li><li><strong>init_per_testcase(TestCase, Config): </strong>Configuration function for a testcase, executed before each test case. (Optional)</li><li><strong>end_per_testcase(TestCase, Config): </strong>Configuration function for a testcase, executed after each test case. (Optional)</li></ul><blockquote><em>For each test case, the Common Test test server expects the following functions:</em></blockquote><ul><li><strong>Testcasename(): </strong>Information function that returns a list of test case properties. (Optional)</li><li><strong>Testcasename(Config): </strong>The test case function.</li></ul><blockquote>Source: <a href="http://erlang.org/documentation/doc-6.3/lib/common_test"><strong>http://erlang.org/documentation/doc-6.3/lib/common_test</strong></a><strong> 1.9/doc/html/basics_chapter.html</strong></blockquote><p><strong>Authors: </strong>Group 10</p><ul><li><a href="http://mustafallica.github.io/">MUSTAFA AL-JABURI</a></li><li><a href="http://www.linkedin.com/in/jillianfredette/">JILLIAN FREDETTE</a></li><li><a href="https://www.linkedin.com/in/sylvia-palos-a16361180">SYLVIA PALOS</a></li><li><a href="https://www.linkedin.com/in/gbaban/">GHADA BABAN</a></li><li><a href="http://linkedin.com/in/adan-ramirez-525330146">ADAN RAMIREZ</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bbfee2af9c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Erlang, Under the hood]]></title>
            <link>https://medium.com/@iqdeveloper/erlang-eb5b28d87453?source=rss-b6fa7363ca32------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb5b28d87453</guid>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Mustafa]]></dc:creator>
            <pubDate>Mon, 25 Feb 2019 02:36:59 GMT</pubDate>
            <atom:updated>2019-02-25T02:36:59.025Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*xQNvG3LdqJ_QV0P6vabPrw.png" /></figure><blockquote>We continue our research about Erlang in 2019, you can read the first chapter from <a href="https://medium.com/@iqdeveloper/erlangcosc4-281c6db607a2">https://medium.com/@iqdeveloper/erlangcosc4-281c6db607a2</a></blockquote><h3><strong>Control Abstraction</strong></h3><p>Control abstraction is fundamental to high-level languages, allowing us to hide procedural data by disregarding the low-level details sparing the programmer from complicated code. By defining our own control constructs programmers can accurately perform well-defined operations such as subroutines, loops, and branch instructions.</p><p>In Erlang higher-order functions or just funs are the basic unit of abstractions, they are used to create your own control abstraction. That way they can can do exactly what you want them to do. Higher-order functions are simply functions that manipulate functions. Funs can be used in various ways, but here will show you how they can be used to create your own control abstraction. We will start by defining a simple fun and assign it to a variable:</p><blockquote>Double = fun(X) -&gt; 3*X end</blockquote><blockquote>After defining the fun we can only apply it to an argument, like this:</blockquote><blockquote>Double(1).</blockquote><blockquote>3</blockquote><p>Now that we have a basic understanding of funs we can start creating our own for statements, if statements, switch statements, or while statements. In Erlang there are no for loops so we have to create our own with funs and a concept called recursion. Creating a for loop is easy in Erlang and it allows us to explicitly define the for loop so we don’t have to rely on a set of predefined set of control abstractions.</p><blockquote>for(0, _) -&gt;</blockquote><blockquote>[ ];</blockquote><blockquote>for (N, Term) when N &gt; 0 -&gt;</blockquote><blockquote>io: fwrite(“Hello World!~n”),</blockquote><blockquote>[Term| for(N-1, Term)].</blockquote><blockquote>start() -&gt;</blockquote><blockquote>for(5, 1).</blockquote><p>Here we defined a recursive function which simulates the implementation of a for loop. We applied a guard to ensure the N or limit is a positive value. We then recursively call the for function and reduce the value of N after each iteration.</p><p>While statement that outputs:</p><p>0</p><p>1</p><p>2</p><p>3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*cmev0UkyPvWyCNEgN8z4WQ.png" /></figure><p>Here we defined a recursive function called while to simulate the implementation of a while statement. We input a list X of integers to our while function. The while functions takes each list value and stores it in the variable Acc. Finally the while loop is called recursively for each value in the list X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*jpWLsPuferVljLs1Qf9ePg.png" /></figure><p>We compare the variables A and B. The -&gt; operator follows the expression and the ; operator follows statement 1. The following -&gt; operator follows the true expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*KaGZ_xbcjsclCPcogHqF8A.png" /></figure><h3>Data Types</h3><p>Data types are an essential part of any programming language, and it’s best to have a thorough understanding of them before utilizing the language. Erlang is dynamically typed so there is no need for explicitly stating your data type, but it is strongly typed so it requires explicit conversion between data types. Below is a list of each data type along with its description and examples of use, after which is a few examples of explicit type conversion.</p><h4><strong>Built-in Data Types</strong></h4><ol><li><strong>Number: there are two types of numeric literals:</strong></li></ol><p>We have two types of number data types. Integer and Float. Below are examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/106/0*UEUwkDA3OmNw05kj" /><figcaption><strong>int</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/122/0*BG1aTUi5g-E9xdMJ" /><figcaption><strong>float</strong></figcaption></figure><p><strong>2. Atom: a literal (a constant with a name) can be any combination of characters but if it does not start with a lowercase letter or contains characters that aren’t alphanumeric, underscore (_), or at (@) then it must be enclosed in single quotes (‘)</strong></p><p>Examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*0qQU4IyokWl88Oyv" /></figure><p><strong>3. Bit String: used to store an area of un-typed memory</strong></p><p>Example of multiple ways to create a bit string of size 3 bits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/0*sebfg_W7T6oGeyPL" /></figure><p><strong>4. Tuple: a compound data type with a fixed number of terms where each term ‘Term’ is an element and the number of elements is the size of the tuple. You can create a tuple by giving it a name and using curly brackets, and separating each element with a comma, Tuple_Name = {element1, element2,…, elementn}.</strong></p><p>Example of creating and using a tuple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*yqYpLdewSx6gBmAW" /></figure><p>Line 1 creates a tuple named ‘T’, lines 2–4 are examples of getting an element of a tuple by its index (note that the index of a tuple starts at 1 and not 0) using the element() built-in function, line 5 is an example of resetting an element in a tuple (if wanted, you can keep the same name ‘T’ instead of ‘T2’), and line 6 and 7 are examples or using the tuple_size() built-in function in Erlang to find the size of a tuple.</p><p><strong>5. Map: a compound data type with a variable number of terms made up of key-value pairs, where each key-value pair is an element and the number of elements is the size of the map. You can create a map by giving it a name, using a pound symbol followed by curly brackets, using the notation key=&gt;value for each element, and separating each element with a comma, Map_Name = #{key1=&gt;value1,…,keyn=&gt;valuen}.</strong></p><p>Example of creating and using a map:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*0xH9ED4vh5npLzcb" /></figure><p>Line 1 creates the map named ‘M’, lines 2–4 show how to get a value of an element from its key using the maps:get() built-in function, line 5 shows how to update a value in the map based on its key using the maps:update() built-in function, and lines 6 and 7 show how to determine the size of a map using the map_size() built-in function.</p><p><strong>6. List: a compound data type with a variable number of terms where each term is an element and the number of elements in the list is the length of the list. The list itself is either an empty list ‘[]’ or ‘[H|T]’ which consists of a head (first element) and a tail (remaining elements) which is also a list if this is a proper list. To Create a list, name it and contain the elements in square brackets and separate the elements by commas.</strong></p><p>Example of creating and using a list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*Q38g41IhQUy176l7" /></figure><p>Line 1 is the creation of a list named ‘L’, line 2 is the separation of the head and tail of L into an element (H) and a list (T), line 3–4 are the contents of the head and tail, line 5 is the creation of a new list ‘L2’ with a new head and the tail from L, line 6 is the creation of another new list ‘L3’ with the head from L and a new tail, and lines 7 and 8 are how you find the length of a list using the length() built-in function.</p><h4><strong>Other Data Types</strong>:</h4><ol><li><strong>Boolean: there is no ‘Boolean’ data type in Erlang, however there are two reserved atoms ‘true’ and ‘false’ which have the typical usability of a boolean.</strong></li></ol><p>Examples of the use of booleans:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/0*IGhIk7kWkhkrxTQd" /></figure><p><strong>2. String: there is no ‘String’ data type in Erlang, however you can enclose a string of characters in double quotes (“) which is shorthand for a list of characters, so for example the string “hello” is actually the list [$h, $e, $l, $l, $o] which is equivalent to [104, 101, 108, 111] which is the list of ASCII values of these characters. Also, two adjacent string literals will be concatenated into one during compilation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/0*K3t1STpHaP0qWPo4" /></figure><p>Line 2 shows how you can use the length() built-in function from the list data type and apply it to the ‘string’ data type, and line 3 shows the concatenation of multiple ‘strings’.</p><p><strong>Built-In Type Conversion Functions</strong></p><p>For each of the built-in data types there are a number of built-in functions that allows for explicit type conversion. Following are these built-in functions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*SOiypvLMUX7a8GBc" /><figcaption><em>Source:</em> <a href="http://erlang.org/doc/reference_manual/users_guide.html">http://erlang.org/doc/reference_manual/users_guide.html</a></figcaption></figure><h3><strong>Data Abstraction in the Language</strong></h3><p>While simple programs are easy to manage and manipulate, larger and complex programs can easily be cluttered and inefficient. Data abstraction, such as modules, classes, and functions make the program less time consuming, easier to manage, and more secure. Procedural abstraction is the most basic examples of data abstraction. In procedural abstraction, code is used to implement basic methods without needing to understand how the method is implemented. These are a few examples of procedural abstraction where they are understood print a certain response but the implementation is not needed to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*KKYqye5RInXJiL5I" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/0*QiIAWRmoBSt8T_4L" /><figcaption>This is given to produce the current date.</figcaption></figure><p>Another key example is Modular abstractions. With modular abstractions, modular code-level functional abstractions, rely on the dialyzer to create them for you like in the queue example from above.</p><p>The date() is given to produce the current date. This particular code could be lengthy due to the method of getting the information from the computer but thankfully the method is already built in and not needed nor important. There is many other basic procedural abstraction that makes it much easier and user friendly to code such as: merge(), add(), List.to_string(), and lists:concat().</p><p>Another key example of data abstraction is modular abstractions.A module is a unit of compilation, where each module is named and contains functions that can be accessed from other modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*ZtrwnrZhML3S_Szi" /></figure><p>This is an example of two modules named main and print. Main is used to create the instances of print and call the message function. Thus whenever M1 is called the value of Name is Humpty and the value of M2 is Dumpty. A feature known as “dynamic code replacement” allows a new version of a module to be loaded at any time. Modules make it much easier and less risky to make changes without affecting the rest of the program.</p><p>Functions are a major contribution to programming. Whether it be a simple adding function or a complex function handling and manipulating large amounts of data, they are able to help make the code shorter and easier to manage. A function that can accept other functions transported around is named a higher order function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*GNKZUr6UsEESz_--" /></figure><p>This is an example of a higher order function. In this example, double() and add_one() are predefined function that are being used in map(). The function-to-function aspect of this code allows for easy manipulation of a certain function without risking the integrity of the other functions.</p><p>Procedural abstraction can be used to write several different functions that have a similar structure, but are slightly different.There are instances in programming where a higher order function is needed for two different functions that are very similar. While these are not exactly the same, they still have separate roles and thus without having to execute each separately, another function may be used to use either or both.</p><p>print_list(Stream, [H|T]) -&gt;<br> io:format(Stream, “~p~n”, [H]),<br> print_list(Stream, T);<br>print_list(Stream, []) -&gt;<br> true.</p><p>broadcast(Msg, [Pid|Pids]) -&gt;<br> Pid ! Msg,<br> broadcast(Msg, Pids);<br>broadcast(_, []) -&gt;<br> true.</p><p>foreach(F, [H|T]) -&gt;<br> F(H),<br> foreach(F, T);<br>foreach(F, []) -&gt;<br> ok.</p><p>foreach(fun(H) -&gt; io:format(S, “~p~n”,[H]) end, L)</p><p>foreach(fun(Pid) -&gt; Pid ! M end, L)</p><p>In this program, print_list() and broadcast() are examples that are similar but slightly different. The function foreach() uses both functions just differently.</p><p>Programs of a certain size are complex. As long as the program is written by a single programmer and is fairly small, say under 1000 lines of code, then everything is easy. The programmer can keep the whole program in the head and it is easy to do stuff with that program. If on the other hand the program grows in size or we add more programmers, then we can’t rely on the singular knowledge of a programmer.</p><p>The only way to solve this problem is to build in abstractions in your programs. We will review two such methods in Erlang. The idea of abstraction, informally, is that we will hide certain details and only provide a clean interface through which to manipulate stuff. Erlang is a “Mutually Consenting Adult Language” (read: dynamically typed with full term introspection — or more violently — unityped crap with everything in one big union type). So this abstraction is not possible in reality. On the other hand, the dialyzer can provide us with much of the necessary tooling for abstraction.</p><p>As an example of so-called modular abstraction, let us consider a small toy module:</p><pre>-module(myq).</pre><pre> -export([push/2,<br>          empty/0,<br>          pop/1]).<br> -type t() :: {fifo, [integer()], [integer()]}.<br> -export_type([t/0]).</pre><pre> -spec empty() -&gt; t().<br> -spec push(integer(), t()) -&gt; t().<br> -spec pop(t())     -&gt; &#39;empty&#39; | {&#39;value&#39;, integer(), t()}.</pre><p>These are the definitions and specs of the module we are implementing. We are writing a simple queue module for a FIFO queue, based on two lists that are kept back-to-back. Using a Standard ML / Ocaml trick here by calling the canonical type it operates on for ‘t’. The operations <em>push/2</em> and <em>pop/1</em> are used to push and pop elements to and from the queue respectively. Note we are prefixing queues by the atom ‘fifo’ to discriminate them from other tuples. The implementation of the queue is equally simple:</p><pre>empty() -&gt; {fifo, [], []}.</pre><pre> push(E, {fifo, Front, Back}) -&gt; {fifo, Front, [E | Back]}.</pre><pre> pop({fifo, [E | N], Back}) -&gt; {value, E, {fifo, N, Back}};<br> pop({fifo, [], []})        -&gt; empty;<br> pop({fifo, [], Back})      -&gt; pop({fifo, lists:reverse(Back), []}).</pre><p>We always push to the back list and always pop from the front list. If the front list ever becomes empty, we reverse the back list to the front. Not used persistently, this queue has amortized O(1) run-time and is as such pretty fast.</p><p>The neat thing is that all operations are local to the myq module when you want to operate on queues. This abstracts away details about queues when you are using them via this module. There can much code inside such a module which is never exposed to the outside and thus we have an easier time managing the program.</p><p>There is a problem with this though, which is that the implementation of the queue is <em>transparent</em>. A user of the myq module can, when handed a queue, Q, of type myq:t() we can discriminate on it like this user:</p><pre>-module(u).</pre><pre> -compile(export_all).</pre><pre> -spec f(myq:t()) -&gt; myq:t().<br> f(Q) -&gt;<br>     case Q of<br>         {fifo, [], []} -&gt;<br>             myq:push(7, Q);<br>         _Otherwise -&gt;<br>             Q<br>     end.</pre><p>Note how we match on the queue and manipulate it. This is <em>bad</em> practice! If the myq module defined the representation of the queue it ought to be the <em>only</em> module that manipulate the internal representation of a queue. Otherwise we might lose the modularity since the representation has bled all over the place. Now, since Erlang is for mutually consenting adults, you need to make sure this data structural representation leak doesn’t happen yourself. It is <em>especially</em> important with records. If you want modular code, avoid putting records in included header files if possible unless you are <em>dead sure</em> the representation won’t change all of a sudden. Otherwise the record will bleed all over your code and make it harder to change stuff later on. Also changes are not module-local but in several modules. This hurts the reusability of code.</p><p>However, the dialyzer has a neat trick! If we instead of</p><pre>-type t() :: {fifo, [integer()], [integer()]}.</pre><p>had defined the type as <em>opaque</em></p><pre>-opaque t() :: {fifo, [integer()], [integer()]}.</pre><p>Then the dialyzer will report the following when run on the code:</p><pre>u.erl:9: The call myq:push(7,Q::{&#39;fifo&#39;,[],[]}) does not have an<br>      opaque term of type myq:t() as 2nd argument</pre><p>which is a warning that we are breaking the opaqueness abstraction of the myq:t() type.</p><p><strong>The Other kind of abstraction in Erlang<br></strong>Languages like Haskell or ML has these kind of tricks up their sleeve in the type system. You can enforce a type to be opaque and get type errors if a user tries to dig into the structure of the representation. Since the dialyzer came later in Erlang one might wonder why one could write programs larger than a million lines of code in Erlang and get away with it when there was no enforcement of opaqueness. The answer is subtle and peculiar. Part of the answer is naturally the functional heritage of Erlang. Functional languages tend to have excellent reusability properties because the task of handling <em>state </em>is diminished. Also, functional code tend to be easier to maintain since it is much more data-flow oriented than control-flow oriented. But Erlang has another kind of abstraction which is pretty unique to it, namely that of a process:</p><p>If we create a process, then its internal state is not observable from the outside. The only thing we can do is to communicate with the process by protocol: we can send it a message and we can await messages from it. This makes the process <em>abstract</em> when viewed from the outside. The internal representation is not visible and you could completely substitute the process for another one without the caller knowing. In Erlang this principle of process isolation is <em>key</em> to the abstractions facilities.</p><p><strong>What does this mean really?</strong><br>Erlang has not one, but two kinds of ways to handle large applications: You can use modules, exports of types and opaqueness constraints to hide representations. While you <em>can</em> break the abstraction, the dialyzer will warn you when you are doing so. This is a compile-time and program-code abstraction facility. Orthogonally to this, a process is a runtime isolation abstraction. It enforces a given protocol at run time which you must abide. It can hide the internal representation of a process. It provides an abstraction facility as well. It is also the base of fault tolerance. If a process dies, only its internal state can be directly affected. Other processes not logically bound to it can still run. It is my hunch that these two tools together is invaluable when it comes to building large Erlang programs, several hundred thousand lines of code — and get away with it!</p><p>So in conclusion: To create modular code-level functional abstractions, rely on the dialyzer to create them for you like in the queue example from above. To create a modular runtime, split your program into processes, where each process handles a concurrent task.</p><h3><strong>Expressions</strong></h3><p>In this section, all valid Erlang expressions are listed. When writing Erlang programs, it is also allowed to use macro- and record expressions. However, these expressions are expanded during compilation and are in that sense not true Erlang expressions.</p><ol><li><strong>Expression Evaluation</strong></li></ol><p>All subexpressions are evaluated before an expression itself is evaluated, unless explicitly stated otherwise. For example, consider the expression:</p><pre>Expr1 + Expr2</pre><p><strong>Expr1</strong> and <strong>Expr2</strong>, which are also expressions, are evaluated first — in any order — before the addition is performed.</p><p>Many of the operators can only be applied to arguments of a certain type. For example, arithmetic operators can only be applied to numbers. An argument of the wrong type causes a <strong>badarg</strong> runtime error.</p><p><strong>2. Terms</strong></p><p>The simplest form of expression is a term, that is an integer, float, atom, string, list, map, or tuple. The return value is the term itself.</p><p><strong>3. Variables</strong></p><p>A variable is an expression. If a variable is bound to a value, the return value is this value. Unbound variables are only allowed in patterns.</p><p>Variables start with an uppercase letter or underscore (_). Variables can contain alphanumeric characters, underscore and @.</p><p>Examples<strong>:</strong></p><pre>X<br>Name1<br>PhoneNumber<br>Phone_number<br>_<br>_Height</pre><p>Variables are bound to values using <strong>pattern matching</strong>. Erlang uses <strong>single assignment</strong>, that is, a variable can only be bound once.</p><p>The <strong>anonymous variable</strong> is denoted by underscore (_) and can be used when a variable is required but its value can be ignored.</p><p>Example:</p><pre>[H|_] = [1,2,3]</pre><p>Variables starting with underscore (_), for example, _Height, are normal variables, not anonymous. They are however ignored by the compiler in the sense that they do not generate any warnings for unused variables.</p><p>Example:</p><p>The following code:</p><pre>member(_, []) -&gt;<br>    [].</pre><p>can be rewritten to be more readable:</p><pre>member(Elem, []) -&gt;<br>    [].</pre><p>This causes a warning for an unused variable, Elem, if the code is compiled with the flagwarn_unused_vars set. Instead, the code can be rewritten to:</p><pre>member(_Elem, []) -&gt;<br>    [].</pre><p>Notice that since variables starting with an underscore are not anonymous, this matches:</p><pre>{_,_} = {1,2}</pre><p>But this fails:</p><pre>{_N,_N} = {1,2}</pre><p>The scope for a variable is its function clause. Variables bound in a branch of an if, case, or receive expression must be bound in all branches to have a value outside the expression. Otherwise they are regarded as ‘unsafe’ outside the expression.</p><p>For the try expression variable scoping is limited so that variables bound in the expression are always ‘unsafe’ outside the expression.</p><p><strong>4. Patterns</strong></p><p>A pattern has the same structure as a term but can contain unbound variables.</p><p><strong>Example:</strong></p><pre>Name1<br>[H|T]<br>{error,Reason}</pre><p>Patterns are allowed in clause heads, case and receive expressions, and match expressions.</p><p>Match Operator = in Patterns</p><p>If Pattern1 and Pattern2 are valid patterns, the following is also a valid pattern:</p><pre>Pattern1 = Pattern2</pre><p>When matched against a term, both Pattern1 and Pattern2 are matched against the term. The idea behind this feature is to avoid reconstruction of terms.</p><p><strong>Example:</strong></p><pre>f({connect,From,To,Number,Options}, To) -&gt;<br>    Signal = {connect,From,To,Number,Options},<br>    ...;<br>f(Signal, To) -&gt;<br>    ignore.</pre><p>can instead be written as</p><pre>f({connect,_,To,_,_} = Signal, To) -&gt;<br>    ...;<br>f(Signal, To) -&gt;<br>    ignore.</pre><p><strong>String Prefix in Patterns</strong></p><p>When matching strings, the following is a valid pattern:</p><pre>f(&quot;prefix&quot; ++ Str) -&gt; ...</pre><p>This is syntactic sugar for the equivalent, but harder to read:</p><pre>f([$p,$r,$e,$f,$i,$x | Str]) -&gt; ...</pre><h4>Expressions in Patterns</h4><p>An arithmetic expression can be used within a pattern if it meets both of the following two conditions:</p><ul><li>It uses only numeric or bitwise operators.</li><li>Its value can be evaluated to a constant when complied.</li></ul><p><strong>Example:</strong></p><pre>case {Value, Result} of<br>    {?THRESHOLD+1, ok} -&gt; ...</pre><p><strong>5. Function Calls</strong></p><pre>ExprF(Expr1,...,ExprN)<br>ExprM:ExprF(Expr1,...,ExprN)</pre><p>In the first form of function calls, ExprM:ExprF(Expr1,...,ExprN), each of ExprMand ExprF must be an atom or an expression that evaluates to an atom. The function is said to be called by using the <strong>fully qualified function name</strong>. This is often referred to as a <strong>remote</strong> or <strong>external function call</strong>.</p><p><strong>Example:</strong></p><pre>lists:keysearch(Name, 1, List)</pre><p>In the second form of function calls, ExprF(Expr1,...,ExprN), ExprF must be an atom or evaluate to a fun.</p><p>If ExprF is an atom, the function is said to be called by using the <strong>implicitly qualified function name</strong>. If the function ExprF is locally defined, it is called. Alternatively, if ExprF is explicitly imported from the M module, M:ExprF(Expr1,...,ExprN) is called. If ExprFis neither declared locally nor explicitly imported, ExprF must be the name of an automatically imported BIF.</p><p><strong>Examples:</strong></p><pre>handle(Msg, State)<br>spawn(m, init, [])</pre><p><strong>Examples</strong> where ExprF is a fun:</p><pre>1&gt; <strong>Fun1 = fun(X) -&gt; X+1 end,</strong><br><strong>Fun1(3).</strong><br>4<br>2&gt; <strong>fun lists:append/2([1,2], [3,4]).</strong><br>[1,2,3,4]<br>3&gt;</pre><p>Notice that when calling a local function, there is a difference between using the implicitly or fully qualified function name. The latter always refers to the latest version of the module. See <strong>Compilation and Code Loading</strong> and <strong>Function Evaluation</strong>.</p><p>Local Function Names Clashing With Auto-Imported BIFs</p><p>If a local function has the same name as an auto-imported BIF, the semantics is that implicitly qualified function calls are directed to the locally defined function, not to the BIF. To avoid confusion, there is a compiler directive available, -compile({no_auto_import,[F/A]}), that makes a BIF not being auto-imported. In certain situations, such a compile-directive is mandatory.</p><p><strong>6. if</strong></p><pre>if<br>    GuardSeq1 -&gt;<br>        Body1;<br>    ...;<br>    GuardSeqN -&gt;<br>        BodyN<br>end</pre><p>The branches of an if-expression are scanned sequentially until a guard sequence GuardSeq that evaluates to true is found. Then the corresponding Body (sequence of expressions separated by &#39;,&#39;) is evaluated.</p><p>The return value of Body is the return value of the if expression.</p><p>If no guard sequence is evaluated as true, an if_clause run-time error occurs. If necessary, the guard expression true can be used in the last branch, as that guard sequence is always true.</p><p><strong>Example:</strong></p><pre>is_greater_than(X, Y) -&gt;<br>    if<br>        X&gt;Y -&gt;<br>            true;<br>        true -&gt; <em>% works as an &#39;else&#39; branch</em><br>            false<br>    end</pre><p><strong>7. Arithmetic Expressions</strong></p><pre><strong>op</strong> Expr<br>Expr1 <strong>op</strong> Expr2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*VN_nR_0GQ06pbmQenKtrcw.png" /></figure><p><strong>Examples:</strong></p><pre>1&gt; <strong>+1.</strong><br>1<br>2&gt; <strong>-1.</strong><br>-1<br>3&gt; <strong>1+1.</strong><br>2<br>4&gt; <strong>4/2.</strong><br>2.0<br>5&gt; <strong>5 div 2.</strong><br>2<br>6&gt; <strong>5 rem 2.</strong><br>1<br>7&gt; <strong>2#10 band 2#01.</strong><br>0<br>8&gt; <strong>2#10 bor 2#01.</strong><br>3<br>9&gt; <strong>a + 10.</strong><br>** exception error: an error occurred when evaluating an arithmetic expression<br>     in operator  +/2<br>        called as a + 10<br>10&gt; <strong>1 bsl (1 bsl 64).</strong><br>** exception error: a system limit has been reached<br>     in operator  bsl/2<br>        called as 1 bsl 18446744073709551616</pre><p><strong>8. Boolean Expressions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Er0QUr0Z4D9LYiUk3_WNCQ.png" /></figure><p><strong>Examples:</strong></p><pre>1&gt; <strong>not true.</strong><br>false<br>2&gt; <strong>true and false.</strong><br>false<br>3&gt; <strong>true xor false.</strong><br>true<br>4&gt; <strong>true or garbage.</strong><br>** exception error: bad argument<br>     in operator  or/2<br>        called as true or garbage</pre><p><strong>9. Catch and Throw</strong></p><pre>catch Expr</pre><p>Returns the value of Expr unless an exception occurs during the evaluation. In that case, the exception is caught.</p><p>For exceptions of class error, that is, run-time errors, {&#39;EXIT&#39;,{Reason,Stack}} is returned.</p><p>For exceptions of class exit, that is, the code called exit(Term), {&#39;EXIT&#39;,Term} is returned.</p><p>For exceptions of class throw, that is the code called throw(Term), Term is returned.</p><p>Reason depends on the type of error that occurred, and Stack is the stack of recent function calls, see <strong>Exit Reasons</strong>.</p><p><strong>Examples:</strong></p><pre>1&gt; <strong>catch 1+2.</strong><br>3<br>2&gt; <strong>catch 1+a.</strong><br>{&#39;EXIT&#39;,{badarith,[...]}}</pre><p>Notice that catch has low precedence and catch subexpressions often needs to be enclosed in a block expression or in parentheses:</p><pre>3&gt; <strong>A = catch 1+2.</strong><br>** 1: syntax error before: &#39;catch&#39; **<br>4&gt; <strong>A = (catch 1+2).</strong><br>3</pre><p>The BIF throw(Any) can be used for non-local return from a function. It must be evaluated within a catch, which returns the value Any.</p><p><strong>Example:</strong></p><pre>5&gt; <strong>catch throw(hello).</strong><br>hello</pre><p>If throw/1 is not evaluated within a catch, a nocatch run-time error occurs.</p><p><strong>10. TRY</strong></p><pre>try Exprs<br>catch<br>    Class1:ExceptionPattern1[:Stacktrace] [when ExceptionGuardSeq1] -&gt;<br>        ExceptionBody1;<br>    ClassN:ExceptionPatternN[:Stacktrace] [when ExceptionGuardSeqN] -&gt;<br>        ExceptionBodyN<br>end</pre><p>This is an enhancement of <strong>catch</strong>. It gives the possibility to:</p><ul><li>Distinguish between different exception classes.</li><li>Choose to handle only the desired ones.</li><li>Passing the others on to an enclosing try or catch, or to default error handling.</li></ul><p>Notice that although the keyword catch is used in the try expression, there is not a catch expression within the try expression.</p><p>It returns the value of Exprs (a sequence of expressions Expr1, ..., ExprN) unless an exception occurs during the evaluation. In that case the exception is caught and the patterns ExceptionPattern with the right exception class Class are sequentially matched against the caught exception. If a match succeeds and the optional guard sequence ExceptionGuardSeq is true, the corresponding ExceptionBody is evaluated to become the return value.</p><p>Stacktrace, if specified, must be the name of a variable (not a pattern). The stack trace is bound to the variable when the corresponding ExceptionPattern matches.</p><p>If an exception occurs during evaluation of Exprs but there is no matching ExceptionPattern of the right Class with a true guard sequence, the exception is passed on as if Exprs had not been enclosed in a try expression.</p><p>If an exception occurs during evaluation of ExceptionBody, it is not caught.</p><p>It is allowed to omit Class and Stacktrace. An omitted Class is shorthand for throw:</p><pre>try Exprs<br>catch<br>    ExceptionPattern1 [when ExceptionGuardSeq1] -&gt;<br>        ExceptionBody1;<br>    ExceptionPatternN [when ExceptionGuardSeqN] -&gt;<br>        ExceptionBodyN<br>end</pre><p>The try expression can have an of section:</p><pre>try Exprs of<br>    Pattern1 [when GuardSeq1] -&gt;<br>        Body1;<br>    ...;<br>    PatternN [when GuardSeqN] -&gt;<br>        BodyN<br>catch<br>    Class1:ExceptionPattern1[:Stacktrace] [when ExceptionGuardSeq1] -&gt;<br>        ExceptionBody1;<br>    ...;<br>    ClassN:ExceptionPatternN[:Stacktrace] [when ExceptionGuardSeqN] -&gt;<br>        ExceptionBodyN<br>end</pre><p>If the evaluation of Exprs succeeds without an exception, the patterns Pattern are sequentially matched against the result in the same way as for a <strong>case</strong> expression, except that if the matching fails, a try_clause run-time error occurs.</p><p>An exception occurring during the evaluation of Body is not caught.</p><p>The try expression can also be augmented with an after section, intended to be used for cleanup with side effects:</p><pre>try Exprs of<br>    Pattern1 [when GuardSeq1] -&gt;<br>        Body1;<br>    ...;<br>    PatternN [when GuardSeqN] -&gt;<br>        BodyN<br>catch<br>    Class1:ExceptionPattern1[:Stacktrace] [when ExceptionGuardSeq1] -&gt;<br>        ExceptionBody1;<br>    ...;<br>    ClassN:ExceptionPatternN[:Stacktrace] [when ExceptionGuardSeqN] -&gt;<br>        ExceptionBodyN<br>after<br>    AfterBody<br>end</pre><p>AfterBody is evaluated after either Body or ExceptionBody, no matter which one. The evaluated value of AfterBody is lost; the return value of the try expression is the same with an after section as without.</p><p>Even if an exception occurs during evaluation of Body or ExceptionBody, AfterBody is evaluated. In this case the exception is passed on after AfterBody has been evaluated, so the exception from the try expression is the same with an after section as without.</p><p>If an exception occurs during evaluation of AfterBody itself, it is not caught. So if AfterBody is evaluated after an exception in Exprs, Body, or ExceptionBody, that exception is lost and masked by the exception in AfterBody.</p><p>The of, catch, and after sections are all optional, as long as there is at least a catchor an after section. So the following are valid try expressions:</p><pre>try Exprs of <br>    Pattern when GuardSeq -&gt; <br>        Body <br>after <br>    AfterBody <br>end<br><br>try Exprs<br>catch <br>    ExpressionPattern -&gt; <br>        ExpressionBody<br>after<br>    AfterBody<br>end<br><br>try Exprs after AfterBody end</pre><p>Next is an example of using after. This closes the file, even in the event of exceptions in file:read/2 or in binary_to_term/1. The exceptions are the same as without the try...after...end expression:</p><pre>termize_file(Name) -&gt;<br>    {ok,F} = file:open(Name, [read,binary]),<br>    try<br>        {ok,Bin} = file:read(F, 1024*1024),<br>        binary_to_term(Bin)<br>    after<br>        file:close(F)<br>    end.</pre><p>Next is an example of using try to emulate catch Expr:</p><pre>try Expr<br>catch<br>    throw:Term -&gt; Term;<br>    exit:Reason -&gt; {&#39;EXIT&#39;,Reason}<br>    error:Reason:Stk -&gt; {&#39;EXIT&#39;,{Reason,Stk}}<br>end</pre><p><strong>11. Block Expressions</strong></p><pre>begin<br>   Expr1,<br>   ...,<br>   ExprN<br>end</pre><p>Block expressions provide a way to group a sequence of expressions, similar to a clause body. The return value is the value of the last expression ExprN.</p><blockquote>For the rest of the expressions, you can check official <a href="http://erlang.org/doc/reference_manual/expressions.html#block-expressions"><strong>Erlang Reference Manual</strong></a></blockquote><p><strong>Authors: </strong>Group 10</p><ul><li><a href="http://mustafallica.github.io/">MUSTAFA AL-JABURI</a></li><li><a href="http://www.linkedin.com/in/jillianfredette/">JILLIAN FREDETTE</a></li><li><a href="https://www.linkedin.com/in/sylvia-palos-a16361180">SYLVIA PALOS</a></li><li><a href="https://www.linkedin.com/in/gbaban/">GHADA BABAN</a></li><li><a href="http://linkedin.com/in/adan-ramirez-525330146">ADAN RAMIREZ</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb5b28d87453" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Erlang in 2019]]></title>
            <link>https://medium.com/@iqdeveloper/erlangcosc4-281c6db607a2?source=rss-b6fa7363ca32------2</link>
            <guid isPermaLink="false">https://medium.com/p/281c6db607a2</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mustafa]]></dc:creator>
            <pubDate>Mon, 18 Feb 2019 03:58:30 GMT</pubDate>
            <atom:updated>2019-04-22T23:42:47.096Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQNvG3LdqJ_QV0P6vabPrw.png" /></figure><h3>History</h3><p>Erlang, or as it is also commonly referred to ‘Erlang/OTP’, is an open-source general-purpose programming language and runtime environment which was originally a proprietary language developed in 1986 for Ericsson, a networking and telecommunications company. The ‘OTP’ part of Erlang refers to Open Telecom Platform which is a the collection of libraries, tools, and middleware which are written in the Erlang language. Because Erlang was developed to work well for a large scale telecommunications company, it has many favorable characteristics. It is particularly well suited to be used for applications which are distributed, fault tolerant, reliable, soft real-time, and concurrent systems.</p><h3>How to install ERLANG on Windows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/0*UsZXAcuItbxzyLSJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*CMvXx-pC5rj8xDCP" /></figure><blockquote>If you want an Editor for Erlang, you can also download Visual Studio Code (VSC) from <a href="https://code.visualstudio.com/download">https://code.visualstudio.com/download</a> and then the Erlang for VSC from <a href="https://marketplace.visualstudio.com/items?itemName=pgourlain.erlang">https://marketplace.visualstudio.com/items?itemName=pgourlain.erlang</a></blockquote><blockquote>Which will allow for easier editing. You will need to configure the erlang extension in VSC by updating the directory location of erl and the default package manager rebar3 if applicable.</blockquote><h3>How to install ERLANG on Linux</h3><p><strong>1 — Adding the Repository</strong></p><pre>$ wget <a href="https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb">https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb</a></pre><pre>$ sudo dpkg -i erlang-solutions_1.0_all.deb</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3dzWx1Eoh4p3Io0li0dYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpzC5Pjz3bk79icVs5a5uw.png" /></figure><p><strong>2 — Install Erlang on Ubuntu</strong></p><p>to install Erlang packages and its dependencies</p><pre>$ sudo apt-get update<br>$ sudo apt-get install erlang</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iW-eTfRAzBN73NnoIR35-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C66g3_KurKKyHsvfvcVOzQ.png" /></figure><p>or install the complete package at once.</p><pre>$ sudo apt-get update<br>$ sudo apt-get install esl-erlang</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqwNNK_LMvOPtMm0nOcEvg.png" /></figure><blockquote><a href="https://packages.erlang-solutions.com/erlang/">reference</a></blockquote><p><strong>We will demonstrate on how to create a hello world app on Linux</strong></p><p>1- Let’s start with hello world program on erlang. First create file helloworld.erl with</p><pre>$ vi helloworld.erl</pre><p>and then we write this code block “remove the %”</p><pre>% hello world program<br>-module(helloworld).<br>-export([start/0]).</pre><pre>start() -&gt;<br>io:fwrite(&quot;Hello World!\n&quot;).</pre><p>Now compile the hello world program using below command.</p><pre>$ erlc helloworld.erl</pre><p>The above command will create a file helloworld.beam. And now the program is ready to run.</p><pre>$ erl -noshell -s helloworld start -s init stop</pre><pre>Hello World!</pre><p>Alternatively, if you would to write your program in the VSC editor, simply create a .erl file named hello and write the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*p7wYWGiExq0MU1Qq" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/0*rptgEBGWVzkAYP1T" /></figure><h3>HOW Erlang</h3><h3>Package manager</h3><p>What is the Package manager? A package manager or package management system is a collection of software tools that automates the process of installing, upgrading, configuring, and removing computer programs for a computer’s operating system in a consistent manner. A package manager deals with packages, distributions of software and data in archive files. Packages contain metadata, such as the software’s name, description of its purpose, version number, vendor, checksum, and a list of dependencies necessary for the software to run properly. Upon installation, metadata is stored in a local package database. Package managers typically maintain a database of software dependencies and version information to prevent software mismatches and missing prerequisites. They work closely with software repositories, binary repository managers, and app stores.</p><p><strong>So what Erlang uses as a package manager?</strong></p><blockquote>Rebar3… This is the name of the main package manager for Erlang.</blockquote><p>Rebar3 is a build tool and package management tool for Erlang. Creating and publishing your Erlang packages is simple thanks to Rebar3 with its plugin to Hex. Let’s make a simple “hello world” package, and feel free to play along at home!</p><p><strong><em>Download Rebar3: </em></strong><a href="http://www.rebar3.org/">http://www.rebar3.org/</a></p><p>or Use the terminal to download it</p><pre>curl -O <a href="https://s3.amazonaws.com/rebar3/rebar3">https://s3.amazonaws.com/rebar3/rebar3</a></pre><p>Use chmod to make it executable, then add it to your environment variable PATH.</p><pre>chmod +x rebar3<br>export PATH=$PATH:your-current-directory</pre><p><strong>Build an Erlang app using Rebar3 package manager.</strong></p><p>Start with the command <em>rebar3 new</em> to generate a new project from the built-in template called <em>app</em>. In this example we are creating a project called <em>myapp</em>. Other available templates are: <em>release, lib, plugin, escript, cmake</em>.</p><pre>$ rebar3 new app myapp<br>===&gt; Writing myapp/src/myapp_app.erl<br>===&gt; Writing myapp/src/myapp_sup.erl<br>===&gt; Writing myapp/src/myapp.app.src<br>===&gt; Writing myapp/rebar.config<br>===&gt; Writing myapp/.gitignore<br>===&gt; Writing myapp/LICENSE<br>===&gt; Writing myapp/README.md</pre><p>Code for your package is placed within the <em>src</em> directory.</p><pre>$ cd myapp<br>$ tree<br>.<br>├── LICENSE<br>├── README.md<br>├── rebar.config<br>└── src<br>    ├── myapp.app.src<br>    ├── myapp_app.erl<br>    └── myapp_sup.erl</pre><p>The convention is to have one <em>.app.src</em> file to define your app as an OTP application, since Rebar3 only handles <a href="http://www.erlang.org/doc/design_principles/applications.html">OTP structured projects</a>. Looks familiar? The file is also Erlang. Check out the full <a href="http://www.erlang.org/doc/design_principles/applications.html#id73836">reference</a> to see what it can contain.</p><pre>$ cat src/myapp.app.src <br>{application, &#39;myapp&#39;,<br> [{description, &quot;An OTP application&quot;},<br>  {vsn, &quot;0.1.0&quot;},<br>  {registered, []},<br>  {mod, {&#39;myapp_app&#39;, []}},<br>  {applications,<br>   [kernel,<br>    stdlib<br>   ]},<br>  {env,[]},<br>  {modules, []}<br> ]}.</pre><p>The code inside of <em>src/myapp_app.erl</em> is pretty bare bones. It just makes sure that you can start and stop your Erlang app:</p><pre>$ cat src/myapp_app.erl <br>-module(&#39;myapp_app&#39;).<br>-behaviour(application).<br>-export([start/2, stop/1]).</pre><pre>start(_StartType, _StartArgs) -&gt;<br>    &#39;myapp_sup&#39;:start_link().</pre><pre>stop(_State) -&gt;<br>    ok.</pre><p>Rebar3 uses a file called <em>rebar.config</em> to specify addition metadata, such as <a href="https://github.com/rebar/rebar/wiki/Dependency-management">dependencies</a>. There are lots of fields <em>rebar.config</em> can contain. To see them all check out the <a href="https://github.com/rebar/rebar/blob/master/rebar.config.sample">full sample</a>.</p><pre>$ cat rebar.config <br>{erl_opts, [debug_info]}.<br>{deps, []}.</pre><p>Now let’s use Rebar3 to start an Erlang shell with your app and the dependencies in the path. Run <em>application:start(myapp).</em> to verify that your app is correctly loaded.</p><pre>$ rebar3 shell<br>===&gt; Verifying dependencies...<br>===&gt; Compiling myapp<br>Erlang R16B03-1 (erts-5.10.4) [source] [64-bit] [smp:8:8] [async-threads:0] [hipe] [kernel-poll:false]</pre><pre>Eshell V5.10.4  (abort with ^G)<br>1&gt; application:start(myapp).<br>ok<br>2&gt; application:stop(myapp). <br>ok<br>3&gt; <br>=INFO REPORT==== 17-Feb-2019::16:14:10 ===<br>    application: myapp<br>    exited: stopped<br>    type: temporary</pre><h3>Erlang Packages</h3><p>We need to install a plugin called <a href="https://github.com/hexpm/rebar3_hex"><em>rebar3_hex</em></a> in order to use fetch and install Erlang packages from <a href="https://hex.pm/">Hex.pm</a>, the Erlang/Elixir package manager. Simply add the following line to your <em>rebar.config</em> file. (You need Erlang version OTP 17.4 and above)</p><pre>{plugins, [rebar3_hex]}.</pre><p>Then run the commend: <em>rebar3 update </em>to enable the plugin.</p><pre>$ rebar3 update<br>===&gt; Fetching jsx ({pkg,&lt;&lt;&quot;jsx&quot;&gt;&gt;,&lt;&lt;&quot;2.6.1&quot;&gt;&gt;})<br>===&gt; Fetching ssl_verify_hostname ({pkg,&lt;&lt;&quot;ssl_verify_hostname&quot;&gt;&gt;,<br>                                           &lt;&lt;&quot;1.0.5&quot;&gt;&gt;})<br>===&gt; Fetching rebar3_hex ({pkg,&lt;&lt;&quot;rebar3_hex&quot;&gt;&gt;,&lt;&lt;&quot;0.6.0&quot;&gt;&gt;})<br>===&gt; Compiling ssl_verify_hostname<br>===&gt; Compiling jsx<br>===&gt; Compiling rebar3_hex<br>===&gt; Updating package index...</pre><p>If you want to avoid this step every time you create a new Erlang app, add the entry to a global <em>rebar.config </em>and place it at:</p><pre>~/.config/rebar3/rebar.config</pre><h3>Finding Erlang packages</h3><p>The search command lets you find remote Erlang packages published on <a href="https://hex.pm/">Hex.pm</a>. You can use regular expression characters in your query:</p><pre>$ rebar3 hex search cowboy<br>cloudi_service_http_cowboy<br>cowboy</pre><h3>Installing packages</h3><p>Rebar3 can download and install the Erlang packages and any necessary dependencies. Add the application names to the <em>deps</em> entry in your <em>rebar.config</em> file, then run the command: <em>rebar3 compile. </em>In this example we are trying to use two Erlang packages called <em>cowboy</em> and <em>meck</em>.</p><pre>{deps, [cowboy, meck]}.</pre><pre>$ rebar3 compile<br>===&gt; Verifying dependencies...<br>===&gt; Fetching ranch ({pkg,&lt;&lt;&quot;ranch&quot;&gt;&gt;,&lt;&lt;&quot;1.0.0&quot;&gt;&gt;})<br>===&gt; Fetching meck ({pkg,&lt;&lt;&quot;meck&quot;&gt;&gt;,&lt;&lt;&quot;0.8.2&quot;&gt;&gt;})<br>===&gt; Fetching cowlib ({pkg,&lt;&lt;&quot;cowlib&quot;&gt;&gt;,&lt;&lt;&quot;1.0.1&quot;&gt;&gt;})<br>===&gt; Fetching cowboy ({pkg,&lt;&lt;&quot;cowboy&quot;&gt;&gt;,&lt;&lt;&quot;1.0.0&quot;&gt;&gt;})<br>===&gt; Compiling cowlib<br>===&gt; Compiling ranch<br>===&gt; Compiling meck<br>===&gt; Compiling cowboy<br>===&gt; Compiling myapp</pre><p>Want to install a specific version of an Erlang package? Write the application name and the version in a tuple. You can browse the available versions of a package at <a href="https://hex.pm/">Hex home page</a>.</p><pre>{deps, [{cowboy, “1.0.2”}, {meck, &quot;0.8.3&quot;}]}.</pre><h3>Listing Installed packages</h3><p>The <em>rebar3 deps</em> command shows your locally installed packages:</p><pre>$ rebar3 deps<br>cowboy (locked package 1.0.0)<br>meck (locked package 0.8.2)</pre><h3>Uninstalling packages</h3><p>To uninstall a package, you have to remove it from the <em>rebar.config</em> file first, then use the command: <em>rebar3 unlock</em>. Here we removed the package <em>meck </em>from our list.</p><pre>$ rebar3 unlock<br>$ rebar3 deps<br>cowboy (locked package 1.0.0)</pre><p><strong>Authors: </strong>Group 10</p><ul><li><a href="http://mustafallica.github.io/">MUSTAFA AL-JABURI</a></li><li><a href="http://www.linkedin.com/in/jillianfredette/">JILLIAN FREDETTE</a></li><li><a href="https://www.linkedin.com/in/sylvia-palos-a16361180">SYLVIA PALOS</a></li><li><a href="https://www.linkedin.com/in/gbaban/">GHADA BABAN</a></li><li><a href="http://linkedin.com/in/adan-ramirez-525330146">ADAN RAMIREZ</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281c6db607a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>