Array.fold<'T,'State> 関数 (F#)

計算にアキュムレータ引数を使用しながら、コレクションの各要素に関数を適用します。入力関数が f で、要素が i0...iN の場合は、f (... (f s i0)...) iN. を計算します。

名前空間/モジュール パス: Microsoft.FSharp.Collections.Array

アセンブリ: FSharp.Core (FSharp.Core.dll 内)

// Signature:
Array.fold : ('State -> 'T -> 'State) -> 'State -> 'T [] -> 'State

// Usage:
Array.fold folder state array

パラメーター

  • folder
    型: 'State -> 'T -> 'State

    入力要素を受け取って状態を更新する関数。

  • state
    型: 'State

    初期状態です。

  • array
    型: 'T[]

    入力配列。

戻り値

最終状態。

解説

この関数は、コンパイルされたアセンブリでは Fold という名前です。F# 以外の言語から、またはリフレクションを使用してこの関数にアクセスする場合は、この名前を使用します。

使用例

次のコードは、Array.fold の使用例です。

let sumArray array = Array.fold (fun acc elem -> acc + elem) 0 array
printfn "Sum of the elements of array %A is %d." [ 1 .. 3 ] (sumArray [| 1 .. 3 |])

// The following example computes the average of a array.
let averageArray array = (Array.fold (fun acc elem -> acc + float elem) 0.0 array / float array.Length)

// The following example computes the standard deviation of a array.
// The standard deviation is computed by taking the square root of the
// sum of the variances, which are the differences between each value
// and the average.
let stdDevArray array =
    let avg = averageArray array
    sqrt (Array.fold (fun acc elem -> acc + (float elem - avg) ** 2.0 ) 0.0 array / float array.Length)

let testArray arrayTest =
    printfn "Array %A average: %f stddev: %f" arrayTest (averageArray arrayTest) (stdDevArray arrayTest)

testArray [|1; 1; 1|]
testArray [|1; 2; 1|]
testArray [|1; 2; 3|]

// Array.fold is the same as to Array.iter when the accumulator is not used.
let printArray array = Array.fold (fun acc elem -> printfn "%A" elem) () array
printArray [|0.0; 1.0; 2.5; 5.1 |]

出力

  
  

プラットフォーム

Windows 8、Windows 7、Windows Server 2012 で Windows Server 2008 R2

バージョン情報

F# コア ライブラリのバージョン

サポート: ポータブル 2.0、4.0

参照

関連項目

Collections.Array モジュール (F#)

Microsoft.FSharp.Collections 名前空間 (F#)