F# 4.5提供Spans、Match!等特性
source link: http://www.infoq.com/cn/news/2018/08/fsharp-4.5-preview?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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.ofVoidPtr
和 NativePtr.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 处手工获取。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK