title: F#: Recursive tree
body: <p>I have a XElement roughly done like this:</p>
  
  <pre><code>&lt;Tasks&gt;
    &lt;Task&gt;
      &lt;Parent&gt;0&lt;/Parent&gt;
      &lt;Id&gt;1&lt;/Id&gt;
    &lt;/Task&gt;
    &lt;Task&gt;
      &lt;Parent&gt;1&lt;/Parent&gt;
      &lt;Id&gt;2&lt;/Id&gt;
    &lt;/Task&gt;
    &lt;Task&gt;
      &lt;Parent&gt;1&lt;/Parent&gt;
      &lt;Id&gt;3&lt;/Id&gt;
    &lt;/Task&gt;
    &lt;Task&gt;
      &lt;Parent&gt;3&lt;/Parent&gt;
      &lt;Id&gt;5&lt;/Id&gt;
    &lt;/Task&gt;
    [..]
  </code></pre>
  
  <p>Each Task Element has a unique Id, some informations I'm not reporting and a parent id. The parent id refers to another task so that it is possible to represent a tree.</p>
  
  <p>I already have a C# function to sort this structure:</p>
  
  <pre><code>    private void SortTask(ref XElement taskOutput, XElement tasks, string parent)
      {
          var children = from t in tasks.Elements("Task")
                         where t.Element("Parent").Value == parent
                         select t;
  
          foreach (XElement task in children.AsEnumerable())
          {
              taskOutput.Add(task);
              SortTask(ref taskOutput, tasks, task.Element("Id").Value);
          }
      }
  </code></pre>
  
  <p>Here I keep invoking recursively the function searching the children elements of each node and adding the to a new XElement called taskOutput. Each time I pass a reference to this new object, the id of the current element (that represent the parent in the next call) and the original XElement with all the tasks.</p>
  
  <p>Now, I thought this would be a good test case to learn a bit about F# simply rewriting this thing in a functional way, but I'm having trouble with it.</p>
  
  <p>This is what I got so far:</p>
  
  <pre><code>type TaskManager(taskListXml) = 
      member o.taskList = XElement.Parse(taskListXml).Elements(XName.op_Implicit("Task"))
  
      member o.Sort =
          let parent =
              o.taskList
              |&gt; Seq.find (fun t -&gt; t.Element(XName.op_Implicit("Parent")).Value.Equals("0"))
          let rec doSort t =
              let parId = t.Element(XName.op_Implicit("Id")).Value
              let children = 
                  o.tasklist
                  |&gt; Seq.filter (fun x -&gt; x.Element(XName.op_Implicit("Parent")).Value.Equals(parId))
                  |&gt; Seq.iter (fun x -&gt; Console.WriteLine(x))
                  |&gt; Seq.iter (fun x -&gt; doSort x)
  </code></pre>
  
  <p>It does not compile specifying that the return type for let (in <code>let children</code>) has an error.</p>
  
  <p>Any help in let me understand this better?
  Thank you very much</p>