9.1.2 appending members using type extensions

Source: Internet
Author: User

9.1.2 appending members using type extensions

As we mentioned in the previous section, you can add members to any F # data type, and now we'll use differential federation to demonstrate. This way you can add members without modifying any of the original code. In this way, we will be able to preserve the original type and the original function declaration, without modification, and then add the members.

We will extend the example of the fifth chapter declaring the schedule type, which represents an event that can occur only once, or repeatedly, or never occurs. In addition to the data types, we have created a function that calculates the next occurrence of an event. Listing 9.4 is a slightly modified version of the code, we make the code more compact, and use simple tool functions to reconstruct the Once branch in pattern matching, and if you want to compare it, the original code is in Listing 5.5.

Listing 9.4 Schedule data types with functions (F #)

Type Schedule = [1] <--declares the original type

| Never

| Once of DateTime

| Repeatedly of DateTime * TimeSpan

Let futureormaxvalue (dt) = [2] <--implementation tool function

if (dt > DateTime.Now) then Dtelse DateTime.MaxValue

Let getnextoccurrence (Schedule) = [3] <--Specifies the behavior of the public

Match schedule with

| Never->datetime.maxvalue

| Once (eventdate)->futureormaxvalue (eventdate)

| Repeatedly (StartDate, interval) –>

Let Secondsfromfirst = (datetime.now-startdate). TotalSeconds

Let q = Max (secondsfromfirst/interval. totalseconds) 0.0

Startdate.addseconds

(interval. TotalSeconds * (Math.floor (q) + 1.0))

The most important change is that we added the tool function futureormaxvalue[2]. This change does not significantly improve readability, just to illustrate the choice. In a more complex project, there are certain tool functions.

The idea is that in a typical F # source file, the type is declared first, then there are a bunch of tool (private) functions, and then the function we want to expose as members [3]. If we want to make use of the method described in the previous section, it is quite difficult to turn the last function into a member. Because a member must be part of a type declaration, however, we usually want to place the tool function between the type and its members!

To solve this problem, you need to use the intrinsic type extension (intrinsic type extensions), which can add members to the type that is declared first in the file. Listing 9.5 shows how we can use the extension for the schedule type.

Listing 9.5 Adding members with intrinsic type extensions (F #)

Type Schedule =

| Never

| Once of DateTime

| Repeatedly of DateTime *timespan

Let futureormaxvalue (dt) =

(...)

Let getnextoccurrence (Schedule) = [1]

(...)

Type Schedule with [2]

Member X.getnextoccurrence () =getnextoccurrence (x) [3]

member X.occursnextweek = | [4]

Getnextoccurrence (x) < DateTime.Now.AddDays (7.0) |

Comparing the code in Listing 9.4, most of it has not changed, for brevity, so omitted; the only increase is the last four lines of code. The first line [2] defines the type extension, telling the F # compiler to add subsequent members to the type of the specified name, followed by a normal member declaration. [3] The implementation of the member is simple because we have implemented the core function as a function [1]. In addition to getting the next time, we have added a property [4], using a private function to check whether the next occurrence is in the next week.

If you have learned C # 3.0, you will find similarities between type extensions and extension methods. Using type extensions, you can add methods and properties to existing types in other assemblies. The situation in the previous checklist is different because we used an intrinsic type extension. This is a special case where the declaration of the original type and the extension are in the same file; In this case, the F # compiler merges two parts of the type into the same class, and we also have access to the private members of the type in the type extension.

Listing 9.6 shows the invocation of the members in Listing 9.5. Members that are added using type extensions behave like other members, so the list has no surprises.

Listing 9.6 using member handling Schedule (F # Interactive)

> Let Sch = repeatedly (Datetime.now,timespan (2, 0, 0, 0));

Val Sch:schedule

> Sch.   Occursnextweek (); <--Testing with recurring events

Val It:bool = True

> Let sch = never;;

Val Sched:schedule

> Sch.   Occursnextweek (); <--testing the behavior of unplanned events

Val It:bool = False

As we work with records, the usual approach is to create F # values, and for the difference in our example, we use the repeatedly or never recognizer (we can also use the Once recognizer). Once we have the value, we can call its members using the object-oriented point symbol.

As we have just seen, members are very useful when writing mature code, because it can wrap code into well-structured pieces to facilitate the use of types. In the development of F #, we usually do not first write the code of the members, only after the code test passed, the addition of members, the API design is fixed. We've discussed two ways to add members:

When the type is simple enough, the member is appended directly to the type declaration.

For complex types, you can change the code less by using an intrinsic type extension.

Type extensions also have the benefit of using the F # Interactive tool to test the type and its handler function before expanding, because we don't have to declare the entire type in one breath.

As we already know, members are important for turning the data-centric F # code into an actual. NET application or component. Now, we will turn our attention to the application of behavioral Center.

9.1.2 appending members using type extensions

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.