代码之家  ›  专栏  ›  技术社区  ›  Michiel Borkent

原型的可枚举#拉入F#?

  •  2
  • Michiel Borkent  · 技术社区  · 16 年前

    在JavaScript中,使用原型库,可以进行以下功能构造:

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

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

    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
    

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

    2 回复  |  直到 13 年前
        1
  •  2
  •   DannyAsher DannyAsher    16 年前

    您可以使用类型扩展和反射来实现这一点。我们使用pull函数简单地扩展了泛型列表类型。然后,我们可以在任何列表中使用pull()。未知属性将返回仅包含错误字符串的列表。

    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>
        2
  •  1
  •   Mike Dunlavey    16 年前

    原型的 pluck 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 这可能会让查看代码的人更加困惑。