Function and functional programming

Source: Internet
Author: User
Tags add time

Function and functional programming

    1. Introduced


Over the past decade, there have been two very well-known programming methods: Object-oriented and process oriented, in fact, either a programming norm or a methodology for programming. And now, a more ancient way of programming: Functional programming, with its non-saving state, non-modification of variables and other features to re-enter the field of vision. Let's take a look at this traditional programming concept in turn, starting with the basic concept of function.


function definition:


Junior high School math function definition: Generally, in a change process, if there are two variables x and Y, and for each definite value of x, Y has a unique value corresponding to it, then we refer to x as the independent variable, y is called the dependent variable, Y is the function of X. The range of values of the argument x is called the definition field of the function.


function definition in programming language: function is a programming method of logical structure and process.

function definition method in Python: Def Test (x): "The function Definitions" x+=1 return x def: the keyword that defines the function test: function name (): Inside definable parameter "": Document description (not necessary, but It is strongly recommended to add descriptive information for your function) X+=1: Refers to the code block or program processing logic return: Define the return value


Add:

Functional programming is: first define a mathematical function, and then follow this mathematical model in the programming language to implement it. As for the specific how to achieve and the benefits of doing so, follow-up I will describe in detail.


Why use a function


No function programming is just writing logic (function), want to break away from the function, reuse your logic, the only way is to copy


Example one:

Suppose we have written a logic (function) to write the log in an appended way: With open (' a.txt ', ' ab ')  as f:    f.write (' End  action ') now has three functions, each of which needs to use this logic after processing its own logic, so the only way is to copy three times this logic def test1 ():     print  ' Test1 starting action ... '         with open ( ' A.txt ', ' ab ')  as f:        f.write (' end action ')      def test2 ():    print  ' test2 starting action ... '         with open (' a.txt ', ' ab ')  as f:         f.write (' end action ')      def test3 ():     print  ' test3 starting action '     with open (' a.txt ', ' AB ')  as f:        f.write (' end action ')    So suppose there's a >n function that needs to use thisLogic, can you copy n times? 


Example two:

Optimized code

Def logger_test (): With open (' a.txt ', ' ab ') as F:f.write (' End Action ') def test1 (): print ' test1 starting action.        .‘ Logger_test () def test2 (): print ' test2 starting action ... ' logger_test () def test3 (): print ' Test3 St Arting action ... ' Logger_test ()


Example three:

The demand has changed (let's add time to the log)

Import Timedef logger_test (): time_format= '%y-%m-%d%x ' Time_current=time.strftime (Time_format) with open (' A.txt ' , ' AB ') as F:f.write (' Time%s End Action '%time_current) def test1 (): print ' test1 starting action ... ' Logger_ Test () def test2 (): print ' test2 starting action ... ' logger_test () def test3 (): print ' test3 starting Action ... ' Logger_test ()


The three advantages of summing up the use of functions in two and three examples

1. Code Reuse

2. Maintain consistency

3. Extensibility


Functions and procedures


Procedure definition: A procedure is simply a function with no return value

So it looks like we're talking about why the functions that we introduced when we used the function didn't return a value, and no return value was the process, yes, but there was something magical in python.


Def test01 (): msg= ' Hello the little green frog ' Print Msgdef test02 (): msg= ' Hello Wudalang ' Print msg retur n msgt1=test01 () t2=test02 () print ' from test01 return was [%s] '%t1print ' from test02 return is [%s] '%t2


Summary: The Python interpreter implicitly returns none when a function/procedure does not return a value using the definition returned by return.

So in Python that is, the process can also be counted as a function.


function return value
Def test01 (): Passdef test02 (): Return 0def test03 (): Return 0,10, ' hello ', [' Alex ', ' lb '],{' wudalang ': ' lb '}t1=test0 1 () t2=test02 () t3=test03 () print ' from test01 return was [%s]: '%type (T1), T1print ' from test02 return is [%s]: '%type (T2), t 2print ' from test03 return is [%s]: '%type (T3), T3


Summarize:

Number of return values = 0: Return None

Number of return values = 1: Return object

Number of return values >1: return tuple


Function call


Call Method:

1.test () execution, () indicates that the call function test, () can have parameters or can not

Parameters:

1. Formal parameters and arguments

Formal parameter: Formal parameters, not actually exist, are virtual variables. Use formal parameters when defining functions and function bodies, in order to receive arguments at function calls (number of arguments, type should correspond to argument one by one)

Arguments: Actual arguments, parameters passed to the function when the function is called, can be constants, variables, expressions, functions, passed to formal arguments

2. Positional parameters and keywords (standard call: Real participation parameter position one by one corresponds; keyword call: position without fixing)

3. Default parameters

4. Parameter groups


Asidifen on time to send a third party event to occur F # with open (' A.txt ', ' WB ') as f:# f.writelines ([' Hello%s lhf\n '%i for I in range (10000)]) with open ('            A.txt ', ' RB ') as f:offset=-100 while True:f.seek (offset,2) l=f.readlines () If Len (l) > 1: LAST_LINE=L[-1] Break offset*=2 print Last_line

This article is from "A Good person" blog, please be sure to keep this source http://egon09.blog.51cto.com/9161406/1834777

Function and functional programming

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.