javascript - F# 中原型(prototype)的 Enumerable#pluck?

标签 javascript f# functional-programming prototypejs

在 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 语法之前,我想我不会再在这里发帖。

关于javascript - F# 中原型(prototype)的 Enumerable#pluck?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76571/

相关文章:

f# - 在 Deedle 系列中计数唯一

c++ - 如何在 C++ 中使用单个模板参数传递两个 lambda 函数

f# - 响应式(Reactive)框架与 F# 事件有何不同?

ios - 在 Swift 中使用嵌套 reduce

haskell - 折叠非列表?

php - 在新页面上将变量从 JavaScript 传递到 PHP

javascript - pushState 问题 Framework7 v3.5.2 不加载 View

javascript - Meteor 应用程序中的用户调度 :phoneformat. js 服务器端

javascript - 触摸移动卡住忽略取消触摸移动的尝试

c# - .NET 列表上的随机访问很慢,但如果我总是引用第一个元素怎么办?