The purpose of this assignment is to get you to create a very simple threaded program in Erlang.
You are to write a module in Erlang, called a3.erl. It will export a function of two arguments, also called a3. a3(N, T) will compute the square root of the sum of the numbers from 1 to N using T threads. You can call it like this:
% erl 1> c(a3). 2> a3:a3(1000000, 10).
where the first line starts the Erlang shell, the second line compiles and loads the module, and the third line calls the function.
The a3/2 function is to create T threads, each knowing the range of numbers it is to work on. When each thread has finished, it is to send its result back to the original thread. The original thread will receive these rules, add them, and return the square root of the sum.
Submit your assignment within one week by sending an
e-mail message to
email@example.com with the
subject "COSC441 Assignment 3" and just the a3.erl file.
Any comments you wish to make should be comments inside
that file. Erlang comments begin with "%" and extend to
the end of the line.
The purpose of this assignment is to get you writing a little Erlang program. It's not supposed to be a puzzle. So here is a quick reference to some of the things you will need, which is why you should only need one week. Get onto it quickly!
factorial(N) when is_integer(N), N >= 0 -> factorial_loop(N, 1). factorial_loop(0, F) -> F; factorial_loop(N, F) -> factorial_loop(N-1, N*F).
a call to factorial(40) will give the answer 815915283247897734345611269596115894272000000000 exactly.
For example, we can define
product(Numbers) -> product(Numbers, 1). product(, Accumulator) -> Accumulator; product([Number | Numbers], Accumulator) -> product(Numbers, Accumulator * Number).
Then we can use the library function lists:seq(From, To) and write
factorial(N) -> product(lists:seq(1, N)).
fun (...) [when ...] -> ... ; (...) [when ...] -> ... ; (...) [when ...] -> ... end
They may have multiple clauses. For example, you could write an anonymous "maximum" function as
fun (X, Y) when X >= Y -> X ; (X, Y) when X =< Y -> Y end
No function has to have more than one clause if you don't want it to.
spawn(fun () -> handler(Lower_Bound, Upper_Bound) end)
Parent = self(), spawn(fun () -> handler(Self, Lower_Bound, Upper_Bound) end)
receive pattern [when guard] -> body ; pattern [when guard] -> body ... [ after timeout -> body end
A clause of a receive expression is selected when there is a message in the caller's mailbox that matches the pattern and makes the guard true. When that happens the message is removed from the mailbox.
-module(name). -export([f1/n1, ..., fk/nk]. function declaration. ...
where -export may be repeated. A function defined inside a module is callable from outside if and only if its name/arity pair is listed in an -export declaration.