2014-02-16 44 views
2

F#新手在這裏,試圖找到'做事的功能性方式'。以標籤爲參數的F#函數

我的記錄

type Node = {Value: int; Height: int; Width: int} 
let dummyData = [| 
    {Value = 1000; Height = 200; Width = 200} 
    {Value = 500; Height = 1000; Width = 500} 
    {Value = 2000; Height = 500; Width = 100} 
    |] 

我期待找到每個在記錄標籤的最小值的數組。對於每一個標籤,我能找到編寫一個函數來找到使用Array.minBy的最低值,例如:

let findMinHeight xs = 
    let item = 
     xs |> Array.minBy (fun x -> x.Height) 
    item.Height 

但是這種感覺很麻煩,因爲在這個例子中我需要基本相同的功能3寫次,每個標籤一次。 是否有可能構造一個函數,該函數將特定標籤和陣列一起接收並返回適當的最小值?

我希望能夠寫類似:

let minHeight = findMin dummyData Height 
let minWidth = findMin dummyData Width 
let minValue = findMin dummyData Value 

回答

3

唱片公司都不是可以作爲函數的參數傳遞「一流」的價值觀。然而,你可以寫一個findMin函數接受另一個函數作爲參數 - 然後給它一個函數,Node,並返回你的記錄的標籤之一:

所以,我們添加Node -> 'T類型的參數f'T類型是泛型類型參數,因此只要它們具有可比性,該函數就可以與不同類型的標籤一起使用)。該功能在minBy用,然後得到所產生的item的財產:

let findMin (f:Node -> 'T) xs = 
    let item = xs |> Array.minBy f 
    f item 

要使用它,你可以寫(我加f作爲第一個參數,所以我們可以使用流水線操作編寫代碼) :

dummyData |> findMin (fun n -> n.Height) 
dummyData |> findMin (fun n -> n.Width)