繁体   English   中英

F# 中原型的 Enumerable#pluck?

[英]Prototype's Enumerable#pluck in F#?

在 JavaScript 中,使用 Prototype 库,以下功能构造是可能的:

var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"];
words.pluck('length');
//-> [7, 8, 5, 16, 4]

请注意,此示例代码等效于

words.map( function(word) { return word.length; } );

我想知道在 F# 中是否有类似的可能:

let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"]
//val words: string list
List.pluck 'Length' words
//int list = [7; 8; 5; 16; 4]

无需编写:

List.map (fun (s:string) -> s.Length) words

这对我来说似乎非常有用,因为这样您就不必为每个属性编写函数来访问它们。

我在 F# 邮件列表上看到了您的请求。 希望我能帮上忙。

您可以使用类型扩展和反射来实现这一点。 我们使用 pluck 函数简单地扩展了通用列表类型。 然后我们可以在任何列表上使用 pluck()。 未知属性将返回一个列表,其中包含错误字符串作为其唯一内容。

type Microsoft.FSharp.Collections.List<'a> with
    member list.pluck property = 
        try 
            let prop = typeof<'a>.GetProperty property 
            [for elm in list -> prop.GetValue(elm, [| |])]
        with e-> 
            [box <| "Error: Property '" + property + "'" + 
                            " not found on type '" + typeof<'a>.Name + "'"]

let a = ["aqueous"; "strength"; "hated"; "sesquicentennial"; "area"]

a.pluck "Length" 
a.pluck "Unknown"

在交互式窗口中产生以下结果:

> a.pluck "Length" ;; 
val it : obj list = [7; 8; 5; 16; 4]

> a.pluck "Unknown";;
val it : obj list = ["Error: Property 'Unknown' not found on type 'String'"]

温暖的问候,

丹尼·阿舍

> > > > >

注意:当使用<pre > 周围的尖括号

<'a>
虽然在预览窗口中没有显示它看起来不错。 反引号对我不起作用。 不得不求助于你的彩色版本,这是完全错误的。 在完全支持 FSharp 语法之前,我不认为我会在这里再次发帖。

Prototype 的pluck利用了 Javascript object.method()object[method]相同的优点。

不幸的是,您也不能调用String.Length ,因为它不是静态方法。 但是,您可以使用:

#r "FSharp.PowerPack.dll" 
open Microsoft.FSharp.Compatibility
words |> List.map String.length 

http://research.microsoft.com/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Compatibility.String.html

但是,使用Compatibility可能会使查看您代码的人更加困惑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM