Javascript 原型&x27;s可枚举的#拉入F#?
在JavaScript中,使用原型库,可以进行以下功能构造:Javascript 原型&x27;s可枚举的#拉入F#?,javascript,f#,functional-programming,prototypejs,Javascript,F#,Functional Programming,Prototypejs,在JavaScript中,使用原型库,可以进行以下功能构造: var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"]; words.pluck('length'); //-> [7, 8, 5, 16, 4] 请注意,此示例代码相当于 words.map( function(word) { return word.length; } ); 我想知道在F#中是否可能有类似的情况: 不用写: List
var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"];
words.pluck('length');
//-> [7, 8, 5, 16, 4]
请注意,此示例代码相当于
words.map( function(word) { return word.length; } );
我想知道在F#中是否可能有类似的情况:
不用写:
List.map (fun (s:string) -> s.Length) words
这对我来说似乎非常有用,因为这样您就不必为每个属性编写函数来访问它们。Prototype的
Pull
利用了Javascript对象中的这一点。method()
与对象[method]
相同
不幸的是,您也不能调用String.Length
,因为它不是静态方法。但是,您可以使用:
#r "FSharp.PowerPack.dll"
open Microsoft.FSharp.Compatibility
words |> List.map String.length
但是,使用
兼容性
可能会让查看您的代码的人更加困惑。我在F#邮件列表上看到了您的请求。希望我能帮忙
您可以使用类型扩展和反射来实现这一点。我们使用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"
键入Microsoft.FSharp.Collections.List.GetProperty属性
[对于列表中的elm->prop.GetValue(elm,[| |]])]
使用e->
[框
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'"]
<'a>