我仍在努力研究F#的事情 - 試圖弄清楚如何在F#中「思考」,而不是僅僅從我認識的其他語言翻譯出來。F#中的移動平均值計算#
我最近一直在考慮你之前和之後沒有1:1地圖的情況。 List.map掉落的情況。
其中一個例子是移動平均值,其中通常在n項中取平均值時,您將獲得長度爲len的列表的len-n + 1個結果。
對於那裏的高手,這是一個很好的方法來做到這一點(使用隊列捏Jomo Fisher)?
//Immutable queue, with added Length member
type Fifo<'a> =
new()={xs=[];rxs=[]}
new(xs,rxs)={xs=xs;rxs=rxs}
val xs: 'a list;
val rxs: 'a list;
static member Empty() = new Fifo<'a>()
member q.IsEmpty = (q.xs = []) && (q.rxs = [])
member q.Enqueue(x) = Fifo(q.xs,x::q.rxs)
member q.Length() = (List.length q.xs) + (List.length q.rxs)
member q.Take() =
if q.IsEmpty then failwith "fifo.Take: empty queue"
else match q.xs with
| [] -> (Fifo(List.rev q.rxs,[])).Take()
| y::ys -> (Fifo(ys, q.rxs)),y
//List module, add function to split one list into two parts (not safe if n > lst length)
module List =
let splitat n lst =
let rec loop acc n lst =
if List.length acc = n then
(List.rev acc, lst)
else
loop (List.hd lst :: acc) n (List.tl lst)
loop [] n lst
//Return list with moving average accross len elements of lst
let MovingAverage (len:int) (lst:float list) =
//ugly mean - including this in Fifo kills genericity
let qMean (q:Fifo<float>) = ((List.sum q.xs) + (List.sum q.rxs))/(float (q.Length()))
//get first part of list to initialise queue
let (init, rest) = List.splitat len lst
//initialise queue with first n items
let q = new Fifo<float>([], init)
//loop through input list, use fifo to push/pull values as they come
let rec loop (acc:float list) ls (q:Fifo<float>) =
match ls with
| [] -> List.rev acc
| h::t ->
let nq = q.Enqueue(h) //enqueue new value
let (nq, _) = nq.Take() //drop old value
loop ((qMean nq)::acc) t nq //tail recursion
loop [qMean q] rest q
//Example usage
MovingAverage 3 [1.;1.;1.;1.;1.;2.;2.;2.;2.;2.]
(也許一個更好的方式是由先進先出繼承來實現MovingAverageQueue?)
非常好,這是幫助我「成長」的那種答案 - 即發現已經存在的東西,而不是重新發明輪子! – Benjol 2008-11-18 06:38:13
死鏈接,我想現在所有的文檔都被移到了msdn,所以類似的頁面將是http://msdn.microsoft.com/en-us/library/dd233209(VS.100).aspx或http:// msdn .Microsoft.com/en-us/library/ee353635(VS.100).aspx – 2010-01-20 02:35:35