In "Programming F#", author Chris Smith on page 37 gives this example of using List.reduce:

let insertCommas (acc : string) item = acc + ", " + item;;

List.reduce insertCommas ["Jack"; "Jill"; "Jim"; "Joe"; "Jane"];;

val it : string = "Jack, Jill, Jim, Joe, Jane"

I understand that insertCommas uses the first item in the list as the initial value of the accumulator "acc", but I don't understand why it chooses the 2nd item of the list as "item". Is it just a convention?

If you look at the definition of List.reduce, you'll see that it's constructed to perform the specified function on the first two elements of the list and then perform the specified function with the result of the first computation and the third element in the list and so on.

If I had code that looked like this:

1
2
3
4
let sum e1 e2 = e1+e2;;

List.reduce sum [1;2;3;4;5];;

I'd expect the result to be 15--and in fact it is.

1
List.reduce

simply recursively applies the specified function to the first two elements in the list and then to the result of that and the next element in the list thereafter. In this particular case, the function calls might be thought of as looking like this:

[i]1st call [/i] sum 1 2

[i]2nd call [/i]

1
sum (sum 1 2)  3

[i]3rd call[/i]

1
sum (sum (sum 1 2) 3) 4

[i]4th call [/i]

1
sum (sum (sum (sum 1 2) 3) 4) 5

I think he calls the first argument [i]acc[/i] because in a sense it holds the accumulated result of the operation.

Hope that helps.

By on 5/7/2010 9:43 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper