手机版
你好,游客 登录 注册
背景:
阅读新闻

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

[日期:2017-02-07] 来源:infoq.com  作者: Pierre-Luc Maheu ,译者 刘嘉洋 [字体:大 中 小]

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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-02/140297.htm

linux
相关资讯       C# 7  F#  F# 4.1 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款