Functional Programming BASICS (F #, JS)

Source: Internet
Author: User

The first three articles are about the functional features of javascript:

    1. Typical high-order functions of JavaScript
    2. Typical higher-order functions of JavaScript
    3. Javascript-based partial application

Simply Review the formal method from the beginning. By the way, we will also review F # And try to use JavaScript to demonstrate it. At the same time, we will also add C # for comparison. For f #, read Wikipedia: F #

Why Learning functional programming? There are too many reasons, and everyone has their own opinions. But for me, I was surprised when I used LINQ and Lambda in C # for the first time. How can this happen? But at that time, I only stayed at the usage level and failed to understand why or how to do it. I didn't really understand it until I learned this course. So this is the reason. It is very simple.

Basic

First, let's take a look at how to define the type. For example, we want to define the type named "day. This "day" can be Monday, Tuesday,..., Sunday. Next, let's take a look at the definitions of the three versions. The first is F #:

1 TypeDay =2|Monday3|Tuesday4|Wednesday5|Thursday6|Friday7|Saturday8| Sunday

In F,TypeIs a keyword of the definition type. The initial letter of the defined constructor must be capitalized. For example, it should be "Monday" rather than "Monday ". "|" Each value following is of the day type. The second is the Javascript version:

 1   VaR Day =Function  (Name ){  2       This . Name = Name;  3   }  4   VaR Monday = New Day ("Monday" ),  5 Tuesday = New Day ("Tuesday" ),  6 Wednesday =New Day ("Wednesday" ),  7 Thursday = New Day ("Thursday" ),  8 Friday = New Day ("Friday" ),  9 Saturday = New Day ("Saturday" ),  10 Sunday = New Day ("Sunday ");

In JavaScript, Day is used as a class, and all others are day instances, which is a little troublesome compared with F. This should be a manifestation, and there are other better ways to tell them. Finally, we are most familiar with C:

 
Abstract ClassDay {}ClassMonday: day {}ClassTuesday: day {}ClassWednesday: day {}ClassThursday: day {}ClassFriday: day {}ClassSaturday: day {}ClassSunday: day {}

in C # Code , the abstract class is used as the type, and all others are inherited from it. Obviously, F # is the most concise in terms of expression ability. When the type is available, define another function that uses this type:

  1   let   next_weekday (D: Day): Day =   2   match  d  with   3  | Monday->  Tuesday   4  | Tuesday->  Wednesday   5  | Wednesday->  Thursday   6  | Thursday->  Friday   7  | Friday->  Monday   8  | Saturday->  Monday   9  | Sunday-> Monday 

The above defines a function named "next_weekday". The following brackets accept a parameter "D", "d: Day". The colon follows the type and ends ": day indicates that the return type of the function is day, and "=" is obviously followed by the function body. The right arrow of "Monday-> Tuesday" in the function body indicates the return value. Therefore, this function is the next "workday", and the next workday on Monday is Tuesday. The "Arrow" is the most natural and direct expression, which is clear at a glance. Let's look at the other two versions:

 1   Function  Next_weekday (d ){  2       Switch  (D. Name ){  3       Case "Monday ": Return   New Day ("Tuesday" );  4      Case "Tuesday ": Return   New Day ("Wednesday" );  5       Case "Wednesday ": Return   New Day ("Thursday" );  6       Case "Thursday ": Return   New Day ("Friday" );  7      Case "Friday ": Return   New Day ("Monday" );  8       Case "Saturday ": Return   New Day ("Monday" );  9       Case "Sunday ": Return   New Day ("Monday" );  10  }  11 }

 Day next_weekday (day d ){  Switch  (D. tostring ()){  Case   "  Monday  " : Return ( New  Tuesday ());  Case   "  Tuesday " : Return ( New  Wednesday ());  Case   "  Wednesday  " : Return ( New  Thursday ());  Case   "  Thursday  " : Return ( New  Friday ());  Case   "  Friday  " : Return ( New  Monday ());  Case   "  Saturday  " : Return ( New Monday ());  Case   "  Sunday  " : Return ( New  Monday ());  Default : Return   Null  ;}} 

After defining the function, you can perform a unit test first. Let's take a look at F # first:

Printfn"% A \ n"(Next_weekday Friday) printfn"% A \ n"(Next_weekday Saturday ))//Result:Mondaytuesday

Similarly, JavaScript and C # testing:

 
Console. Log (next_weekday (Friday); console. Log (next_weekday (Saturday )));//Result:Day {name: "Monday"} Day {Name:"Tuesday "}

1Console. writeline (next_weekday (NewFriday ()));2Console. writeline (next_weekday (NewSaturday ())));

 
//Result:
Monday
Tuesday

The test results are all OK. Using F # is the most concise. The semantics is also the most direct. I don't know if you will fall in love with F. Define another type. Only the Boolean types of true and false are defined. We all know that this type is not available except for the C language, and other languages are built in. Now let's implement it ourselves:

 
Type Bool=|True| False
VaRBool =Function(B ){If(B = "true" | B = "false ")This. Name =B ;}
 
Abstract ClassBools {}ClassTrue {}ClassFalse {}

In C #, bool is the keyword, so it is changed to bools. If we leave the logic behind, it seems meaningless to only look at the type, and it does not reflect the Boolean features at all. Therefore, some helper functions are added to express these features. They are: reverse, or, and operations.

 Let Negb (B: Bool ): Bool =  Match B With | True-> False | False-> True  Let Andb (B1: Bool ) (B2: Bool ): Bool  =  Match B1 With | True-> B2 | False-> False Let ORB (B1: Bool ) (B2: Bool ): Bool  =  Match B1 With | True-> True | False-> B2
 Function  Negb (B ){  If (B. Name = "true ") Return   New Bool ("false" ); If (B. Name = "false ") Return   New Bool ("true" );}  Function  Andb (b1, b2 ){  If (B1.name = "true ") Return  B2;  Else   Return   New Bool ("false" );}  Function  ORB (b1, b2 ){ If (B1.name = "true ") Return   New Bool ("true" );  Else   Return  B2 ;} 
 Bools negb (bools B ){  If (B. GetType (). tostring () = "  False  "  )  Return   New True ();  Return   New  False ();}  Bools andb (bools B1, bools B2 ){  If (B1.gettype (). tostring () = "  False  "  )  Return   New  False ();  Return  B2 ;} Bools ORB (bools B1, bools B2 ){  If (B1.gettype (). tostring () = "  True  "  )  Return   New  True ();  Return  B2 ;} 

The test and result will not be posted. The above mainly involves some type definition work. I feel a little strange when Javascript is implemented. readers understand that this is a weakness and an advantage! F # It is very straightforward and concise when defining a type. C # is mainly defined by struct or class. Or F # is more popular :)

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.