我仍在努力理解F#的东西——尝试弄清楚如何“思考”F#,而不仅仅是从我知道的其他语言进行翻译。
最近,我一直在思考那些没有一对一映射的情况。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.]
也许更好的方法是通过继承Fifo来实现一个MovingAverageQueue?
let MovingAverage n (s : seq<float>) =
,以便将其放置在实用程序模块中,远离调用站点,以安抚类型系统。据我所知,这仅适用于浮点数,因为Array.average
存在限制。MSDN 声称我可以使用Array.averageBy
替换它,以在 int 序列上使用此函数,但是那会导致不同的错误。Brian,你能否重新构造这个答案,使其适用于任何算术类型的序列,而不需要类型推断? - Warren Young