Difference between fold and reduce?

前端 未结 4 837
囚心锁ツ
囚心锁ツ 2020-12-13 05:12

Trying to learn F# but got confused when trying to distinguish between fold and reduce. Fold seems to do the same thing but takes an extra parameter. Is there a legitimate r

4条回答
  •  情深已故
    2020-12-13 06:01

    In addition to what Lee said, you can define reduce in terms of fold, but not (easily) the other way round:

    let reduce f list = 
      match list with
      | head::tail -> List.fold f head tail
      | [] -> failwith "The list was empty!"
    

    The fact that fold takes an explicit initial value for the accumulator also means that the result of the fold function can have a different type than the type of values in the list. For example, you can use accumulator of type string to concatenate all numbers in a list into a textual representation:

    [1 .. 10] |> List.fold (fun str n -> str + "," + (string n)) ""
    

    When using reduce, the type of accumulator is the same as the type of values in the list - this means that if you have a list of numbers, the result will have to be a number. To implement the previous sample, you'd have to convert the numbers to string first and then accumulate:

    [1 .. 10] |> List.map string
              |> List.reduce (fun s1 s2 -> s1 + "," + s2)
    

提交回复
热议问题