List.fold<'T,'State> 함수(F#)

업데이트: 2010년 5월

컬렉션의 각 요소에 함수 f를 적용하여 계산을 통해 누적기 인수를 스레딩합니다. fold 함수는 두 번째 인수를 받고 해당 인수와 목록의 첫 번째 요소에 함수 f를 적용합니다. 그런 다음 이 결과를 두 번째 요소와 함께 f 함수에 제공하는 식으로 진행합니다. 최종 결과를 반환합니다. 입력 함수가 f이고 요소가 i0...iN이면 이 함수는 f (... (f s i0) i1 ...) iN을 계산합니다.

네임스페이스/모듈 경로: Microsoft.FSharp.Collections.List

어셈블리: FSharp.Core(FSharp.Core.dll)

// Signature:
List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State

// Usage:
List.fold folder state list

매개 변수

  • folder
    형식: 'State -> 'T -> 'State

    지정된 입력 요소의 상태를 업데이트하는 함수입니다.

  • state
    형식: 'State

    초기 상태입니다.

  • list
    형식: 'T list

    입력 목록입니다.

반환 값

최종 상태 값입니다.

설명

컴파일된 어셈블리에서 이 함수의 이름은 Fold입니다. F# 이외의 언어에서 함수에 액세스하거나 리플렉션을 통해 함수에 액세스하는 경우 이 이름을 사용합니다.

예제

다음 예제에서는 List.fold를 사용하는 방법을 보여 줍니다.

let data = [("Cats",4);
            ("Dogs",5);
            ("Mice",3);
            ("Elephants",2)]
let count = List.fold (fun acc (nm,x) -> acc+x) 0 data
printfn "Total number of animals: %d" count
  

다음 코드 예제에서는 List.fold의 다른 용도를 보여 줍니다. 아래 구현된 기능을 이미 캡슐화한 라이브러리 함수만 존재합니다. 예를 들어, 목록의 모든 요소를 더하는 데 List.sum을 사용할 수 있습니다.

let sumList list = List.fold (fun acc elem -> acc + elem) 0 list
printfn "Sum of the elements of list %A is %d." [ 1 .. 3 ] (sumList [ 1 .. 3 ])

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

// The following example computes the standard deviation of a list.
// 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 stdDevList list =
    let avg = averageList list
    sqrt (List.fold (fun acc elem -> acc + (float elem - avg) ** 2.0 ) 0.0 list / float list.Length)

let testList listTest =
    printfn "List %A average: %f stddev: %f" listTest (averageList listTest) (stdDevList listTest)

testList [1; 1; 1]
testList [1; 2; 1]
testList [1; 2; 3]

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

// The following example uses List.fold to reverse a list.
// The accumulator starts out as the empty list, and the function uses the cons operator
// to add each successive element to the head of the accumulator list, resulting in a
// reversed form of the list.
let reverseList list = List.fold (fun acc elem -> elem::acc) [] list
printfn "%A" (reverseList [1 .. 10])

Output

      

플랫폼

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

버전 정보

F# 런타임

지원되는 버전: 2.0, 4.0

Silverlight

지원되는 버전: 3

참고 항목

참조

Collections.List 모듈(F#)

Microsoft.FSharp.Collections 네임스페이스(F#)

변경 기록

날짜

변경 내용

이유

2010년 5월

코드 예제를 추가했습니다.

향상된 기능 관련 정보