CARVIEW |
Recent Activity
Related
-
Thinking in Erlang
151 reads -
Erlang [Read Only]
434 reads -
Embarking on the Road of Intrusion Detection, With Erlang
0 reads -
Erlang at Facebook
1110 reads -
Erlang Intro
39 reads -
Numerical Comparison Between Erlang and C++
241 reads -
null
175 reads -
null
193 reads -
null
177 reads -
Hacking Erlang
314 reads -
Inside the Erlang VM
395 reads -
Using Erlang In A Web Startup - A Hypernumbers Whitepaper
36 reads -
Hypernumbers Whitepaper - Using Erlang In Web Startups
18 reads -
Call Center Mathematics
84 reads -
The Life and Works of a.K. Erlang
219 reads
More from this user
Featured on Scribd
. {CustId. In our example.5] and [4. 363 defined. calls the handle function. or. but when testing with records from the shell. AllowedRestarts. Mnesia is the brainchild of Claes “Klacke” Wikström* from the days when he was working at Ericsson’s Computer Science Lab. we’ll discuss this shortly). The following example of list comprehensions. you can use erlang:demonitor(Reference. . We discuss optimizations in Chapter 20 and will cover there what really affects the performance of your code. set_service/3.12. tuesday.5}.erl:110: The pattern [] can never match the type {'error'. 0).name=Name}) -> io:format("name: ~p age: ~p phone: ~p~n". Value}. will be traversed only once. To quote Joe Armstrong in one of the many type system flame wars.116. The following code shows the conversion to this representation:
treeToList({leaf. the system will not maintain a global list of connected nodes. which isolates it from the higher levels of the system. Buffer) -> lists:reverse(Buffer). We will provide more examples in Chapter 11."Hello ok 4> inet:getstat(Socket). You will also get more flexible code. [binary. stop(_State) -> ok. List)
Removes all elements in the list for which Predicate is false. Considering that this target has been achieved at a fraction of the effort that would have been needed in a conventional programming language.2. TypEr was applied to a version of usr_db without type annotations. terminate/2. Ericsson’s Computer Science Laboratory was given the task of investigating programming languages suitable for programming the next generation of telecom products.[2. VarN need to begin with a capital letter. is passed as the third argument to the handle_call/3 function. if you have many recipients or are forwarding the unchanged message to many processes. you can access it using either the name or the table identifier. you can just bind them to a variable.erlang-consulting. . because in a live system. 212 bitwise operators. allocate} -> {NewFrequencies.cook}]
This is a list of guard expressions. .100.ok} 3> timer:tc(myring. N}.bad_day}}]. and bind it to the variable A.
Using passive mode is a good way to ensure that your system does not get flooded with requests. average_acc([]. -> index(N-1. So. Sverker Eriksson. The lecturer held up the first edition of Concurrent Programming in Erlang (Prentice Hall) and said. you might not find the priv directory. Translations to match specifications are done at compile time. critics said it was madness to use a language compiling for a VM with a garbage collector (just like Java!) for soft real-time systems. duplicate_bag
Including one of these in the options list creates an ETS table of the specified sort.. overwriting the entry in the peer node.do_apply. 260 trunc/1 function. Once the connection has been established. which involves process linking and supervision. {shell. sos]). 3]) => sum([1. . which returns on success the tuple {value. %% Internal Server Functions
240 | Chapter 10: ETS and Dets Tables
init(FileName. you can omit the of. The default size of an integer is 8.daisy}]}. 447 handle function. we need a local get_index/1 call.atom} 4> io:read("ok. Luckily. ok 2> my_db:write(foo.
A common trick to reduce indentation is to create temporary composite data types.NET platform. Fields}. As soon as you turn on trace printouts. false 10> lists:member(24.acm.. and loop/0.
Exercises | 393
CHAPTER 18
Types and Documentation
The basic types in Erlang—integers. . not only are programs shorter and easier to understand. status=enabled. 250 string comparison. and as you can see from the following example.|.
In practice. {shell. return a new list that is the symmetric difference of the two lists. .2}. and Event Types
The Erlang wx binding allows events to be handled in two ways. Now that we’ve looked at ETS and Dets tables in detail.1 of the db module. Request} -> Reply = request(Request).
| or +
You can use these to form the union of two types. symbols.msisdn}]). using the flush() command in the shell. but one of the really powerful features of the trace BIFs. and Haskell: The Craft of Functional Programming. delete_usr/1. At its best performance. For large binaries. the two mandatory applications of any OTP release. so we define a new helper function. the BIF self() returns a pid. Frequency}. usr_db]}. Two functions in the same module might have the same name but a different arity. 1. send email to: bookquestions@oreilly. whether it is a function call. we could have replaced all of the ETS and Dets read.2]. and different instances of these callback modules could exist in different managers.. E2. 14 Thompson. There are many features and details we have not covered. .loop. F. [{exception. there should be no module X.
Exercise 7-4: Records and Shapes
Define a record type to represent circles. Var2. If you are fast enough. not a fun that is bound to a variable which is then passed as an argument.
User Datagram Protocol | 325
and sending [0. In a tuple.kill) is used. Many Erlang processes will fall into one of these three categories. In this example. It is a common design pattern to spawn a new process that handles the request for each message received. 148–154 message passing. 1.
To connect a process with pid Pid to a port Port. 'Mike'.
this time using guards:
factorial(N) when N > 0 -> N * factorial(N . despite being appended to the Help menu in setup. 378 add_handler function.{name. You have to be careful when using timeouts. or the atom error otherwise. We will store it as an integer in the ETS table.VarN).false).
So. you can try them out in the shell to be sure you understand what is going on:
16> Bump = fun(X) -> X+1 end. . you would have [11.Y*X.6. Mnesia chapter exercises.eval_loop. user status. 110 creating. and the loop/1 function is called recursively with the updated loop data. 3. for example. . For example. Moreover. go() -> Pid = spawn(echo. init(Data) -> loop(initialize(Data)).2. we need to lock the tables using the safe_fixtable/2 call. This should generate random store and lookup requests. described in Chapter 14. The call returns the atom ok. . ++ included. 49–50 runtime errors. Rest) -> gen_tcp:send(Socket. the code is more easily modified if the composition of the record is changed or extended.tftp_binary. starting at zero. We want to compute the average of a list of numbers.31> 3> receive {'DOWN'.hrl"). 75. . bnot. factorial(N) -> N * factorial(N-1). 'Armstrong'} {person. suspending it in the receive clause. normal. and what are the contents of the app file? Let’s start with the application callback file. lines 18–26. can be complex at times. we’ll revisit the example of the factorial server just given for Java. no abbreviations used by the tracer tool are allowed. use the literal function bindings(). and are what we refer to as internal help functions: • If there are no available frequencies.3]. 700000003}) end). Function. With lightweight processes.
Distributed Computing in Erlang: The Basics
An Erlang node is an executing Erlang runtime system that has been given a name. is not pretty. which works in a similar way to function clause selection.
Now. In an example such as the index. This guarantee is not extended to messages sent from different processes. creating what is called a supervision tree (see Figure 12-1). resp). All of the functions that change the database state are synchronously executed by the database server to guarantee data consistency:
add_usr(PhoneNum.. as in this C++ example:
File->Append(NEW. ringing(Number). will be in one of three states.. {error. treeToList(tree1())). How should protocols ensure that data is generated and transmitted as quickly and efficiently as possible? The answer is to make use of every possible bit of storage. Wildcards need to follow the preceding pattern. allowing DECT cordless phone users to roam across private office networks. 225–226. Erlang terms can be simple data values. The error report shown in the shell comes from the add_one process. the local variable X in Bump shadows the earlier X. or structured? Is an integer in Java the same thing as an integer in Erlang? (It isn’t!) Interoperation is not only about interlanguage communication.0. The . You should ensure that the expression is evaluated only once whichever case holds. . If you want to override one of the modules in a sticky directory. an Erlang open source Jabber-based instant messaging (IM) server. They are. for the example in Figure 9-1 this would begin "{node. A race condition occurs when the behavior of a system depends on the order in which certain events occur: these events “race” to influence the behavior.[binary_to_list(Msg)]) 1> end. The guards allowed in literal funs are the same as in conventional guards. if. . The only difference between this and the nondistributed case is that a remote node may become unavailable. the call will immediately return the atom ok...{size.
Exercise 3-5: Manipulating Lists
Write a function that.erlang. 296 table structure. 8 interfaces defined.BStr.
And Finally.
Upon receiving the messages.Reason} signal is the process identifier of the receiving process itself. 157 functions and.sweden}). [p. as shown here?
erlang:trace_pattern({ping. 342 erl_marshal function.16. ok. except that the Pid in the {'EXIT'. CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) On the web page for this book we list errata.‡ In your case.erl %%% Description : API and server code for cell user db -module(usr). Notice how memory is allocated in the old heap while being freed in the current heap. Pid} -> [{Pid. and not simply in a single module.lbs]}. in the dbg:fun2ms/1 fun body call. To construct the same term manually. Before starting to look at lists. . dets:close(subDisk). all processes that are waiting for or holding the semaphore are allowed to complete their tasks. . LoopData) -> {ok. . 1.0> 5> ping:send(Pid).app file.# When you do so. experimenting with insertion. then>>"). Pid}. By only handling positive cases where the structure is correctly parsed. . Name}. Arity}). DataOffset:4. meaning “all fields that are not explicitly mentioned” are matched to a wildcard. if there is no other traffic. It is stripped down so that all it can do is display an About box.
Exercise 3-4: Database Handling Using Lists
Write a module db. whereas an enter_window event will also have associated with it the position of the mouse when the event occurred (among other things).catch construct. often follow standards and application-level protocols that allow programs written independently of each other to interact with each other. 343. The effect of this is as follows:
248 | Chapter 11: Distributed Programming in Erlang
1.eval_loop. all you need to do is ensure that there is no schema directory for that particular node. Fd) -> Fd. you might not enjoy the trail of peace and tranquility the call leaves behind. where we retrieve only the messages we are explicitly interested in based on certain criteria. Here is the code from Chapter 5. 349 bit sequences. Which one of them do you prefer?
154 | Chapter 6: Process Error Handling
Exercise 6-3: A Supervisor Process
The supervisor we provided in the example is very basic. either constructing a new list or calculating a value. We say that process A depends on process B when the fact of B terminating can prevent A from functioning correctly. race conditions can occur.{2008. it can be linked to the supervision tree. Socket.
Let’s take a closer look at how this evaluates:
even([10. 65 2> $A + 32. true}
Ensures that the connected socket sends keepalive messages when no data is being transferred. . process) process manager (pman). math:pi()*2*2. where the first element is the construct and the remaining ones are the logical expressions.0> global_group:init/1 71 0 <0. {num. first for intermodule calls. {put_chars. Device drivers are typically written in C. true
The ability to compare values from different data types allows you to write generic functions such as sort. Use it in a safe test environment as carelessly as you want. Modules are your basic building blocks. .. With a Prolog-based Erlang virtual machine (VM). after which it saves the data to a file.
Indexing
When creating the usr table. Pid ! stop. You can use the ping method on a node to test whether a remote node exists.return_error.4. one for each entry. Had you been using transactions. on the other hand. Instead. 31 variables. In the early days. and events triggered by the passage of time or by external user gestures with a mouse or keyboard. The home page of the Erlang online documentation
installed.null]}.228}. and messages to denote events. 182 worker. {error. increment the head. as Erlang had all of the qualities he was looking for in a database application. use the code:unstick_dir(Dir) call or start Erlang using the –nostick flag.98. all of which are read and executed at startup. Mnesia might not be the right choice."Armstrong".[]. given a list of lists.
1. {NextWord. In turn.
74 | Chapter 3: Sequential Erlang
Let’s try catching exceptions by using the list_to_integer/1 BIF. disabled). These macros include the following:
debugVal(Expr)
Will print the source code and current value of Expr. There are two variants of the system on Windows.age. return(X) when is_integer(X) -> catch return_error(X). of course.0).{size.72}. 'Armstrong'}. World"} World"} World"} World"}
332 | Chapter 15: Socket Programming
{send_oct. 445 Index . 378 is_record function. or its definition. And most importantly. However. stopping. . you are presented with a list of all the applications running on all distributed nodes. A shallow garbage collection looks only at data in the youngest generation. sum(6. and behaviour for now. and lbs allows third parties to execute location lookups on this particular user. Args). register(add_two. Oscar Hellström.5.W) when ?Multiple(Z. you must benchmark whole systems in the application domain for which those languages were designed. where he has taught computing at undergraduate and postgraduate levels for the past 25 years. the shell commands rf(RecordName) and rf() forget one or all of the record definitions currently visible in the shell. compile it in the same shell where we ran the previous iteration.{1.. https://www.3. Element]. %% The client Functions
150 | Chapter 6: Process Error Handling
stop() -> call(stop). 421 development considerations.
Tracing Local and Global Function Calls
So far. .[{usr. The system will create a node with the default cookie if none is supplied when the node is started.
send(Socket. you will discover that there are many variants of the tp.41. instance} 4> my_db:read(foo).108. 342. It allows a programmer to traverse a data structure via successive calls to the same function. Example:
reverse([1. running in a separate operating system thread (see Figure 16-1). [harryPotter. where you do not want to affect the state of the process you are calling and don’t want it to receive an exit signal if the client terminates as a result of a link to another process. 371 palin/1 function. and training and systems development. The various language features covered in this chapter. you are bound to come across this."
The ++ operator takes two lists and joins them together into a new list. but also in a degradation of the performance of the operations applied on the table.5}. Once you’ve created an atom. If you type the same code in a module as part of a function and compile it.104.0. 338 RPC support. . A. 80 single assignment. We could also call this an “explicit” or a “manifest” fun. "length ( [ 1 . N}.{cat. respectively. or just an integer. 41 compile:file function. Pid = spawn(?MODULE.
Exercises | 243
CHAPTER 11
Distributed Programming in Erlang
To write a fault-tolerant system. we’ll use the example of an index. [] -> {error. If you are interested in reading more about other Internet Protocol implementations. . and reverse. but there will be some surprises. 302–304 ETS tables and. You can access this page at: https://www.<0.10. Using case studies from commercial. we clean up by removing the file UsrTabFile. wxFrame:show(Frame). shared between connected nodes so that if A knows about B.{Word. There
226 | Chapter 10: ETS and Dets Tables
is a catch. thus reducing the risk of bugs. In our example.21. beta. Payload). remove.128. 160 implementing. .8] should return [4. Given the data structure returned by the dict module. Now that we can insert data. This fault tolerance allows the system to be more robust and reliable. [Size2|_] = TTL2. benchmarks show that Erlang manages to outperform these languages for the same reasons it outperforms them in process creation times. or existing. and the time/0 function returns the current time as a tuple of {Hour. But now. When changing a float to an integer.3}
badarg
This is returned when a BIF is called with the wrong arguments.<0. A number of the format 071234567 is thus represented as 71234567. preferred(X) -> Y = case X of one -> 12._. . 416 assertNot macro. whereas false will disable it. 437 error handling.00000 7> 2*2*3. loop. 367 set_on_spawn flag. Options)
This will run the command Cmd as an external program. .. let’s look at how you access the documentation associated with them. . true.otp. We start the event manager with the log_handler. and cannot occur within function definitions. Large Erlang systems consist of loosely coupled Erlang modules. . .
411
The implementer benefits from such an approach because she has a clear target at each stage: pass the tests. or worse. LoopData}. 205 serializing. Richard Carlson.
30 | Chapter 2: Basic Erlang
are trying to execute on the variable. . . and it is now supported by a team of approximately 20 developers and a wide circle of contributors. {stdlib. Occurrences must precede the module declaration itself. prepay). are implemented in the runtime system for efficiency. 380 messages node communications. Conditions. but this is not necessary. {shell. writing "Hello " "Concurrent " "World" will result in the compiler appending the three strings together. 417 test-generating function. Node) -> {facserver. Radius}) -> Side * Side . The handle_cast/1 callback function handles the specifics of the message.and disk-efficient storage and retrieval of large collections of data.
Defensive Programming
Assume your program has to map to an integer an atom representing a day of the week. where we covered distributed Erlang. and which can be left unchanged?
168 | Chapter 7: Records and Macros
Exercise 7-2: Record Guards
Using the record BIF record(P. Allocated}.
The Erlang approach is to use standard return values of the form ok. {ok.Reason} is sent to the monitoring process.
nil()
Has one element.111.m.g. It is the responsibility of the calling process to guarantee that these preconditions are met. are not allowed. 23 Erlang type notation. Languages that don’t provide these tools put a huge burden on developers and support engineers alike. Count]). and open source projects. Double} [true. including those consisting of binary chunks. just as an OTP application will do. So. Functions that have side effects require a more complex infrastructure..[{vsn. You can avoid this problem by using references and assuming that no other processes will send messages of the format {reply. true 21> lists:all(Positive. X has the value 10 as passed in by the parameter.B. For more information on the Inets application. 264 ETS and Dets tables. and traverse them.0}. {reply. .
Two processes that have each created a separate server will not be able to share objects. Pay special attention to the different memory types. you can see a list comprehension appear as part of the result expression. and all the ways in which X can be inserted into that permutation. The following code style is a typical example of what happens when someone writes code. reverse it. -spec delete_usr(_) -> 'ok' | {'error'.11. you do not need to check the return value of each recursive call for an error. 362 reverse function. the underlying TCP buffer can be used to throttle the requests and reject messages on the client side. we will stick to describing supervision within the OTP framework. When destroy is invoked. so to avoid terminating.protected}] 4> ets:info(usrRam). [{shoeSize. as both distributed Erlang nodes share the same root directory. Message) gen_server:call(Name. Communication with linked-in drivers uses ports and the same BIFs as used in port programs. contains information on your application resources and dependencies. Act I
As an example of ETS tables in use.[{new.111.'$2'}.0). . is_atom(X) . 24 4> bnot 9. But that is exactly what the bump function is supposed to do! The solution is to call the function we are defining recursively using the tail of the list:
bump([Head | Tail]) -> [Head + 1 | bump(Tail)]. The pattern matching fails. You should use this if there is a strong dependency among all of the children regardless of the order in which they were started. Send email to index@oreilly.F. he started his career as an intern at Ericsson’s computer science lab. with more complex graphical entities.. meaning they can be called from outside the module.10} 4> frequency:allocate().[c]). even if called more than once in the same microsecond. closed} -> handle(lists:reverse(BinaryList). as they are meant to be accessible outside the module. but it has the disadvantage of making it harder to meet certain lower-level. bags. Usr). . san_francisco. finite state machines.integer()) -> ok|{error.0. returning true if the element is a member of the list and false if not. 408 running.
exit
This can be raised by calling the exit/1 BIF. 276– 280 tail recursion. as generated from a file that begins like this:
@author Francesco Cesarini
-
Reads:
5,653 -
Rated:
-
Published:
07 / 07 / 2009 -
Category:
Description:
This book offers you an in-depth explanation of Erlang, a programming language ideal for any situation where concurrency, fault-tolerance, and fast response is essential. You'll learn how to write ...
Description:
This book offers you an in-depth explanation of Erlang, a programming language ideal for any situation where concurrency, fault-tolerance, and fast response is essential. You'll learn how to write complex concurrent programs in this language, regardless of your programming background or experience. Erlang Programming focuses on the language's syntax and semantics, and explains pattern matching, proper lists, recursion, debugging, networking, and concurrency, with exercises at the end of each chapter.
This book is an in-depth introduction to Erlang, a programming language ideal for any situation where concurrency, fault tolerance, and fast response is essential. Erlang is gaining widespread adoption with the advent of multi-core processors and their new scalable approach to concurrency. With this guide you'll learn how to write complex concurrent programs in Erlang, regardless of your programming background or experience.
Written by leaders of the international Erlang community -- and based on their training material -- Erlang Programming focuses on the language's syntax and semantics, and explains pattern matching, proper lists, recursion, debugging, networking, and concurrency.
This book helps you:
* Understand the strengths of Erlang and why its designers included specific features
* Learn the concepts behind concurrency and Erlang's way of handling it
* Write efficient Erlang programs while keeping code neat and readable
* Discover how Erlang fills the requirements for distributed systems
* Add simple graphical user interfaces with little effort
* Learn Erlang's tracing mechanisms for debugging concurrent and distributed systems
* Use the built-in Mnesia database and other table storage features
Erlang Programming provides exercises at the end of each chapter and simple examples throughout the book.
Tags:
Groups:
Copyright:

Sign up
Use your Facebook login and see what your friends are reading and sharing.
Signup
I don't have a Facebook account
Why Sign up?
![]() |
Discover and connect with people of similar interests. |
![]() |
Publish your documents quickly and easily. |
![]() |
Share your reading interests on Scribd and social sites. |
![]() |
Already have a Scribd account?
Login Successful
Now bringing you back...

Reset your password
Please enter your email address below to reset your password. We will send you an email with instructions on how to continue.
O'Reilly left a comment