簡體   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