歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> F# 4.1提供改善,並支持與C# 7的互操作

F# 4.1提供改善,並支持與C# 7的互操作

日期:2017/3/1 9:05:43   编辑:Linux編程

F# 4.1對語言進行了很多改進。F# 4.1將通過新版本的Microsoft tools for F#提供,Microsoft tools for F#據說將於今年晚些時候發布。該版本支持結構體元組(struct tuples),與C# 7的互操作,以及by-ref返回。

由於F#的語法和類型推斷簡化了元組的使用,元組通常在F#中使用。它們是存儲在堆棧上的引用類型。F# 4.1中提供了存儲在堆棧上的結構體元組。對於某些場景來說,性能得到了提升,比如說需要分配大量的小元組。

要支持ValueTuple類型,元組類型、元組表達式和元組模式可以用關鍵字struct來注釋。

// Creating a new struct tuple.
let origin = struct (0, 0)

// Take struct tuples as arguments to a function and generate a new struct tuple.
let getPointFromOffset (point: struct (x, y)) (offset: struct (dx, dy)) = 
    struct (x + dx, y + dy)

// Pattern match on a struct tuple.
let doAMatch (input: struct (x, y)) =
    match input with
    | struct (0, 0) -> sprintf "The tuple is the origin!"
    | struct (_, _) -> sprintf "The tuple is NOT the origin!"

與C# 7的互操作也支持使用struct關鍵字。

// Calls a C# function returning a value tuple
let struct(word, value) = SomeService.SomeResult()
// Calls a C# function taking a value tuple in parameter.
let result = SomeService.CreateResult(struct("hello", 12))

除了元組之外,記錄類型和可區分聯合也可以表示為值類型。它需要struct注釋。

 [<Struct>]
 type Student = {
    Id: int
    Name: string
    Age: int
    GPA: double
    Major: string
}

[<Struct>]
type Shape = 
| Circle of radius: float
| Square of side: int
| Rectangle of sides: double*double

F# 4.1也提供by-ref返回。F#已經支持了ref locals,但是不支持使用或生成byref-returning方法。

// Returns from an array.
let f (x:int[]) = &x.[0]

// Returns from a record
[<Struct>]
type R = { mutable z : int }
let f (x:byref<R>) = &x.z

by-ref返回也可以在C#的方法中使用。

public static ref int Find(int val, int[] vals)
{
    for (int i = 0; i < vals.Length; i++)
    {
        if (vals[i] == val)
        {
            return ref numbers[i];
        }
    }
}

// 'result' is of type 'byref<int>'.
let result = SomeCSharpClass.Find(3, [| 1; 2; 3; 4; 5 |])

除了GitHub上公布的F#源代碼,你也可以參考公開的語言規范獲取更多信息。

查看英文原文:F# 4.1 Brings Improvements and Interoperation with C# 7

Copyright © Linux教程網 All Rights Reserved