I have been dabbling with F# in Visual Studio 2010. I am a developer with more code/architecture design experience in object-oriented languages such as C# and Java.
T
let createPeople filter = new XElement(XName.Get("People"),
ppl |> List.filter(filter) |> List.map createPerson
)
This part can be deforested manually, or you can hope that the compiler will deforest it for you.
Basically, there is an intermediate structure (the list of filtered people) that, if this is compiled naively, will be allocated to serve only once. Better apply createPerson
on each element as it is decided if they are in or out, and build the final result directly.
EDIT:
cfern contributed this deforested version of createPeople
:
let createPeople filter =
new XElement(
XName.Get("People"),
List.foldBack
(fun P acc -> if filter P then (createPerson P)::acc else acc)
ppl
[])
NOTE: because there could be side-effects in filter
or createPerson
, in F# it is rather hard for the compiler to decide to deforest by itself. In this case it seems to me that deforesting is correct because even if filter
has side-effects, createPerson
doesn't but I'm no specialist.