6 people like it.

Moving average

Saw a Moving Average example on this site ( http://fssnip.net/4S ) and wondered if it could be done in even fewer lines of code. It can. This is why I love F#!

1: 
2: 
3: 
let movingAverage (period : int) (values : float seq) =
    Seq.windowed period values
    |> Seq.map (fun x -> Array.average x)
val movingAverage : period:int -> values:seq<float> -> seq<float>

Full name: Script.movingAverage
val period : int
Multiple items
val int : value:'T -> int (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.int

--------------------
type int = int32

Full name: Microsoft.FSharp.Core.int

--------------------
type int<'Measure> = int

Full name: Microsoft.FSharp.Core.int<_>
val values : seq<float>
Multiple items
val float : value:'T -> float (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.float

--------------------
type float = System.Double

Full name: Microsoft.FSharp.Core.float

--------------------
type float<'Measure> = float

Full name: Microsoft.FSharp.Core.float<_>
Multiple items
val seq : sequence:seq<'T> -> seq<'T>

Full name: Microsoft.FSharp.Core.Operators.seq

--------------------
type seq<'T> = System.Collections.Generic.IEnumerable<'T>

Full name: Microsoft.FSharp.Collections.seq<_>
module Seq

from Microsoft.FSharp.Collections
val windowed : windowSize:int -> source:seq<'T> -> seq<'T []>

Full name: Microsoft.FSharp.Collections.Seq.windowed
val map : mapping:('T -> 'U) -> source:seq<'T> -> seq<'U>

Full name: Microsoft.FSharp.Collections.Seq.map
val x : float []
module Array

from Microsoft.FSharp.Collections
val average : array:'T [] -> 'T (requires member ( + ) and member DivideByInt and member get_Zero)

Full name: Microsoft.FSharp.Collections.Array.average
Raw view New version

More information

Link:http://fssnip.net/5R
Posted:8 years ago
Author:Paul Papathomas
Tags: seq average