Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Erlang (programming language)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Functional programming examples== ===Factorial=== A [[factorial]] algorithm implemented in Erlang: <syntaxhighlight lang="erlang"> -module(fact). % This is the file 'fact.erl', the module and the filename must match -export([fac/1]). % This exports the function 'fac' of arity 1 (1 parameter, no type, no name) fac(0) -> 1; % If 0, then return 1, otherwise (note the semicolon ; meaning 'else') fac(N) when N > 0, is_integer(N) -> N * fac(N-1). % Recursively determine, then return the result % (note the period . meaning 'endif' or 'function end') %% This function will crash if anything other than a nonnegative integer is given. %% It illustrates the "Let it crash" philosophy of Erlang. </syntaxhighlight> ===Fibonacci sequence=== A tail recursive algorithm that produces the [[Fibonacci sequence]]: <syntaxhighlight lang="erlang"> %% The module declaration must match the file name "series.erl" -module(series). %% The export statement contains a list of all those functions that form %% the module's public API. In this case, this module exposes a single %% function called fib that takes 1 argument (I.E. has an arity of 1) %% The general syntax for -export is a list containing the name and %% arity of each public function -export([fib/1]). %% --------------------------------------------------------------------- %% Public API %% --------------------------------------------------------------------- %% Handle cases in which fib/1 receives specific values %% The order in which these function signatures are declared is a vital %% part of this module's functionality %% If fib/1 receives a negative number, then return the atom err_neg_val %% Normally, such defensive coding is discouraged due to Erlang's 'Let %% it Crash' philosophy, but here the result would be an infinite loop. fib(N) when N < 0 -> err_neg_val; %% If fib/1 is passed precisely the integer 0, then return 0 fib(0) -> 0; %% For all other values, call the private function fib_int/3 to perform %% the calculation fib(N) -> fib_int(N-1, 0, 1). %% --------------------------------------------------------------------- %% Private API %% --------------------------------------------------------------------- %% If fib_int/3 receives 0 as its first argument, then we're done, so %% return the value in argument B. The second argument is denoted _ to %% disregard its value. fib_int(0, _, B) -> B; %% For all other argument combinations, recursively call fib_int/3 %% where each call does the following: %% - decrement counter N %% - pass the third argument as the new second argument %% - pass the sum of the second and third arguments as the new %% third argument fib_int(N, A, B) -> fib_int(N-1, B, A+B). </syntaxhighlight> Omitting the comments gives a much shorter program. <syntaxhighlight lang="erlang"> -module(series). -export([fib/1]). fib(N) when N < 0 -> err_neg_val; fib(0) -> 0; fib(N) -> fib_int(N-1, 0, 1). fib_int(0, _, B) -> B; fib_int(N, A, B) -> fib_int(N-1, B, A+B). </syntaxhighlight> ===Quicksort=== [[Quicksort]] in Erlang, using [[list comprehension]]:<ref>{{cite web |url=http://erlang.org/doc/programming_examples/list_comprehensions.html |title=Erlang β List Comprehensions |website=erlang.org}}</ref> <syntaxhighlight lang="erlang"> %% qsort:qsort(List) %% Sort a list of items -module(qsort). % This is the file 'qsort.erl' -export([qsort/1]). % A function 'qsort' with 1 parameter is exported (no type, no name) qsort([]) -> []; % If the list [] is empty, return an empty list (nothing to sort) qsort([Pivot|Rest]) -> % Compose recursively a list with 'Front' for all elements that should be before 'Pivot' % then 'Pivot' then 'Back' for all elements that should be after 'Pivot' qsort([Front || Front <- Rest, Front < Pivot]) ++ [Pivot] ++ qsort([Back || Back <- Rest, Back >= Pivot]). </syntaxhighlight> The above example recursively invokes the function <code>qsort</code> until nothing remains to be sorted. The expression <code>[Front || Front <- Rest, Front < Pivot]</code> is a [[list comprehension]], meaning "Construct a list of elements <code>Front</code> such that <code>Front</code> is a member of <code>Rest</code>, and <code>Front</code> is less than <code>Pivot</code>." <code>++</code> is the list concatenation operator. A comparison function can be used for more complicated structures for the sake of readability. The following code would sort lists according to length: <syntaxhighlight lang="erlang"> % This is file 'listsort.erl' (the compiler is made this way) -module(listsort). % Export 'by_length' with 1 parameter (don't care about the type and name) -export([by_length/1]). by_length(Lists) -> % Use 'qsort/2' and provides an anonymous function as a parameter qsort(Lists, fun(A,B) -> length(A) < length(B) end). qsort([], _)-> []; % If list is empty, return an empty list (ignore the second parameter) qsort([Pivot|Rest], Smaller) -> % Partition list with 'Smaller' elements in front of 'Pivot' and not-'Smaller' elements % after 'Pivot' and sort the sublists. qsort([X || X <- Rest, Smaller(X,Pivot)], Smaller) ++ [Pivot] ++ qsort([Y || Y <- Rest, not(Smaller(Y, Pivot))], Smaller). </syntaxhighlight> A <code>Pivot</code> is taken from the first parameter given to <code>qsort()</code> and the rest of <code>Lists</code> is named <code>Rest</code>. Note that the expression <syntaxhighlight lang="erlang">[X || X <- Rest, Smaller(X,Pivot)]</syntaxhighlight> is no different in form from <syntaxhighlight lang="erlang">[Front || Front <- Rest, Front < Pivot]</syntaxhighlight> (in the previous example) except for the use of a comparison function in the last part, saying "Construct a list of elements <code>X</code> such that <code>X</code> is a member of <code>Rest</code>, and <code>Smaller</code> is true", with <code>Smaller</code> being defined earlier as <syntaxhighlight lang="erlang">fun(A,B) -> length(A) < length(B) end</syntaxhighlight> The [[anonymous function]] is named <code>Smaller</code> in the parameter list of the second definition of <code>qsort</code> so that it can be referenced by that name within that function. It is not named in the first definition of <code>qsort</code>, which deals with the base case of an empty list and thus has no need of this function, let alone a name for it.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)