F# 4.5提供Spans、Match!等特性

栏目: ASP.NET · 发布时间: 7年前

内容简介:类型类型

F# 4.5预览版现已发布 ,其中提供了一系列新特性,包括对.NET Core 2.1的新原生类型 Span<T> 的支持、新关键字 Match! 等。

类型 Span 意在实现底层代码指针操作的安全性和可预测性,这可使得很多情况下不必再分配内存,进而改进了内存使用的效率和性能。为实现此, Span 会为已在内存某处存储的数据提供一种虚拟视图。例如,对于一个具有10000个元素的数组,我们完全可以创建一个包括其前1000个元素的切片,并将该切片传递给函数,不需要对这些元素做拷贝。代码如下:

let nativeMemory = Marshal.AllocHGlobal(100);
    let nativeSpan = new Span<byte>(nativeMemory.ToPointer(), 100)
    let nativeSpanSlice = new Span<byte>(nativeMemory.ToPointer(), 10)
    let mem = NativePtr.stackalloc<byte>(100)
    let mem2 = mem |> NativePtr.toVoidPtr
    let stackSpan = Span<byte>(mem2, 100)

类型 Span 实际上包括了一系列的子特性,例如 voidptr 类型、 NativePtr.ofVoidPtrNativePtr.toVoidPtr 函数,以及其它一些支持F# 4.5的 Span 与C# 7.3对等的特性。特性对应表如下所示:

C#                       F#
out int arg              arg: byref<int>
out int arg              arg: outref<int>
in int arg               arg: inref<int>
ref readonly int         Inferred or arg: inref<int>
ref expr                 &expr

为确保代码的公平性,F#对使用 Span 强加了一系列应用于所有类 byref 结构的限制:

let
byref
byref
byref

关键字 Match! 是开发人员期待已久的一个特性,它用于在 计算表达式 中简化匹配语法。F# 4.1中,在做匹配前,需要使用 let! 作为一个中间步骤:

let funcWithString (s: string) =
    async {
        let! r = asyncFunction s
        match r with
        | Some bananaString -> printfn "It's banana!"
        | None -> printfn "%s" s
    }

而在F# 4.5中,只需如下编写:

let funcWithString (s: string) =
    async { 
        match! asyncFunction s with
        | Some bananaString -> printfn "It's banana!"
        | None -> printfn "%s" s
}

F# 4.5还提供了下列特性:

  • 在序列、列表和数组中使用 yield 时,不再需要做向上造型(upcast)。例如:
let x2 : obj list  = [ yield "a" :> obj ] // F# 4.5版本之前。
let x3 : obj list  = [ yield "a" ] // F# 4.5版本。
public

据Carter介绍,目前发布的F# 4.5非常稳定,它将会加入到即将发布的Visual Studio 2017 update 15.8中。此外,该预览版可以从 .NET Core平台Windows 处手工获取。

查看英文原文: F# 4.5 Brings Spans, Match!, and More


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning ASP.NET 4 in C# and Vb

Beginning ASP.NET 4 in C# and Vb

Imar Spaanjaars / Wrox / 2010-3-19 / GBP 29.99

This book is for anyone who wants to learn how to build rich and interactive web sites that run on the Microsoft platform. With the knowledge you gain from this book, you create a great foundation to ......一起来看看 《Beginning ASP.NET 4 in C# and Vb》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

html转js在线工具
html转js在线工具

html转js在线工具