【问题标题】:Prototype's Enumerable#pluck in F#?F# 中原型的 Enumerable#pluck?
【发布时间】:2010-09-09 17:55:20
【问题描述】:

在 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

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

【问题讨论】:

    标签: javascript f# functional-programming prototypejs


    【解决方案1】:

    我在 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 "长度" ;; 验证它:obj 列表 = [7; 8个; 5个; 16; 4] > a.pluck "未知";; 验证它:obj list = [“错误:在类型'String'上找不到属性'Unknown'”]

    热烈的问候,

    丹尼阿舍

    > > > > >

    注意:当使用&lt;pre> 时,尖括号围绕

     没有显示,但在预览窗口中看起来不错。反引号对我不起作用。不得不求助于你的彩色版本,这是完全错误的。在完全支持 FSharp 语法之前,我想我不会再在这里发帖了。
        

    【讨论】:

      【解决方案2】:

      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 可能会使查看您的代码的人更加困惑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 1970-01-01
        • 2012-04-01
        • 2017-07-14
        • 2013-11-19
        相关资源
        最近更新 更多