Coding Practice for F#

后端 未结 4 1106
礼貌的吻别
礼貌的吻别 2021-02-04 10:44

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 11:33

    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.

提交回复
热议问题