你可以使用mutable
變量和使用for
循環,就像在C#編寫的代碼。但是,如果您正在學習F#和功能概念,那麼使用遞歸是個好主意。
在這種情況下,遞歸函數稍微長一些,但它演示了包括模式匹配在內的關鍵概念 - 因此學習這些技巧在編寫更復雜的F#代碼時會很有用。
關鍵的想法是編寫一個函數,該函數採用迄今爲止發現的最大值並遞歸調用自身,直到它到達列表的末尾。
let max_list list =
// Inner recursive function that takes the largest value found so far
// and a list to be processed (if it is empty, it returns 'maxSoFar')
let rec loop maxSoFar list =
match list with
// If the head value is greater than what we found so far, use it as new greater
| head::tail when head > maxSoFar -> loop head tail
// If the head is smaller, use the previous maxSoFar value
| _::tail -> loop maxSoFar tail
// At the end, just return the largest value found so far
| [] -> maxSoFar
// Start with head as the greatest and tail as the rest to be processed
// (fails for empty list - but you could match here to give better error)
loop (List.head list) (List.tail list)
作爲最後一點,這會很慢,因爲它使用通用比較(通過接口)。您可以使用let inline max_list list = (...)
使功能更快。這樣,代碼將使用本機比較指令時,與基本類型如int
(這是一個非常特殊的情況 - 問題只發生在通用比較)
我假設你不想簡單地調用['List。最大'](http://msdn.microsoft.com/en-us/library/vstudio/ee370242.aspx),對不對? – svick
這是正確的 – Jacco