# 如何在列表中查找函數最大值的值

To illustrate with an example, I want to be able to map a list domain and a function f

let domain = [0 .. 5]
let f x = -x * (x - 2)


（1,1）（因為應用於列表的其他元素的函數小於1）。

let findMaximum domain f =
let candidates = [ for x in domain do
yield x, f x ]
let rec findMaximumHelper domain f currentMax =
match domain with
| [] -> currentMax
let cand = f head
match currentMax with
| None ->
let newMax = Some(head, cand)
findMaximumHelper tail f newMax
| Some(maxAt, possMax) ->
let newMax =
if cand > possMax then Some(head, cand)
else Some(maxAt, possMax)
findMaximumHelper tail f newMax
findMaximumHelper domain f None

let answer = findMaximum domain f


let findMaximum2 domain f =
let findMaximumHelper f acc x =
let cand = f x
match acc with
| None -> Some(x, cand)
| Some(maxAt, possMax) ->
if cand > possMax then Some(x, cand)
else Some(maxAt, possMax)
List.fold (findMaximumHelper f) None domain

let answer2 = findMaximum2 domain f


## 最佳答案

domain
|> Seq.map (fun x -> x, f x)
|> Seq.maxBy snd


Note: updated to use Seq.map and Seq.maxBy instead of List.map and List.maxBy to address @ildjarn's concern about creating an unnecessary intermediate list.