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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…