Section two modules and functions (top)

Source: Internet
Author: User
Tags hypot pear

Module

The module is the basic unit of code for Erlang. The module is saved in a file with the. erl extension and must be compiled before the code in the module can be run. The compiled module has a. beam as the extension.

We create a Geometry.erl file

1 -module  (geometry). 2 -export ([AREA/1]). 3 4 area ({rectangle,width,height})    ,    Width * Height; 5 Area ({square, Side})    ,    Side * Side.

Then compile the module in the shell and run it.

1> c (geometry).
{Ok,geometry}
2> Geometry:area ({rectangle, 10, 5}).
50
3> Geometry:area ({square,4}).
16

The first line of C (file name) is to compile the code inside the file, and the successful run will return the result of {ok,xxxxxx}. Generate a target code module for. Beam at the same time.

In the second line we invoke the function in the module by the way of the file name: Method (Parameter). (Note that you need to attach a module name to the function name so that you can accurately indicate which function you want to call).

Next, we try to add some simple test modules to the module. Name the previous module Geometry_test.erl

  1 -module   -export  ([Test/0,area/1]).   4  test ()-> 5  = Area ({rectangle, 3, 4  6  144 = Area ({square, 12  7   tests_worked.    9  area ({rectangle,width,height})- > Width * Height;  10  area ({square, Side}), Side * Side. 

Then we compile the module in the shell and run it if we get the word test_worked, that means the test passed.

1> C (geometry_test).
{Ok,geometry_test}
2> Geometry_test:text ().
* * Exception error:undefined function geometry_test:text/0
3> geometry_test:test ().
Tests_worked

If you enter the wrong function name in the shell, you will be prompted with an error.

Let's extend the previous function by adding an area ({Circle, radius}), 3.14159 * radius * radius. The order of the clauses to be added does not matter. The program is a meaning regardless of how the clauses are arranged, because each pattern in the clause is mutually exclusive. This allows us to write extensions a lot simpler.

Finally look at our module, we will find a comma (,) semicolon (;) period (.) Such a symbol.

The comma (,) separates the function calls, the data constructs, and the parameters in the pattern.

A semicolon (;) delimited clause.

Period (.) Separates the function as a whole.

Fun: the basic abstract Unit

Erlang is a functional programming language. In addition, functional programming languages indicate that a function can be used as an argument to another function, or it can return a function. Functions that manipulate other functions are called higher-order functions, whereas the data types used in Erlang to represent functions are called fun.

1. Perform the same action on each element in the list.

2. Create your own control abstraction. (There is no for loop in Erlang)

3. Implement reentrant parsing code, parsing a composition, or a lazy evaluation device.

1> Double = Fun (X), 2*x end.
#Fun <erl_eval.6.54118792>
2> Double (2).
4

The above is a way to define a fun in the shell.

Let's take a look at defining what 2 parameters are.

3> Hypot = Fun (X, Y), math:sqrt (x*x + y*y) end.
#Fun <erl_eval.12.54118792>
4> hypot (3,4).
5.0

Next we take fun as a parameter. The lists module in the standard library derives some functions that take fun as parameters. The most useful among them is Lists:map (f,l). This function returns a list that is generated by applying fun F to each element in the list L.

5> L = [1,2,3,4].
[1,2,3,4]
6> Lists:map (Fun (X), 2*x end, L).
[2,4,6,8]

Another useful function is Lists:filter (p, L), which returns a new list containing all the eligible elements in L (conditional P (e) is true for element e).

even = Fun (x)--(x REM 2) =:= 0 end.

Defines a function even (x), which returns True if X is an even number. REM calculates the remainder after dividing by 2, and =:= is used to test for equality.

Then we use map and filter as parameters.

10> Lists:map (even, [1,2,3,4,5,6,8]).
[False,true,false,true,false,true,true]
11> Lists:filter (even, [1,2,3,4,5,6,8]).
[2,4,6,8]

The function can not only use fun as a parameter, but also return fun.

12> Fruit = [Apple,pear,orange].
[Apple,pear,orange]
13> maketest = Fun (L)--(Fun (x), Lists:member (x, L) end) end.
#Fun <erl_eval.6.54118792>
14> isfruit = Maketest (Fruit).
#Fun <erl_eval.6.54118792>
15> isfruit (Pear).
True
16> Isfruit (apple).
True
17> isfruit (dog).
False

Remember that what is in parentheses is the return value.

Let's implement a custom control abstraction, but so far in Erlang we haven't seen an if statement, a switch statement, a for statement, or a while statement, and all of this is written with pattern matching and higher-order functions. We implement a for structure module ourselves.

1 -module  (lib_misc). 2 -export ([FOR/3]). 3 4 for (Max, Max, F)    ,    [F (max)]; 5 for (I, Max, F)        and    [F (i) | for (i+1, Max, F)].

Then execute the module on the shell.

1> lib_misc:for (1,10,fun (i), I end).
[1,2,3,4,5,6,7,8,9,10]
2> lib_misc:for (1,10,fun (I), I*i end).
[1,4,9,16,25,36,49,64,81,100]

Section two modules and functions (top)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.