I'm new to F# and learning the basics.
I have two modules. A generic one for tree data structures called Tree
:
module Tree
let rec getDescendants getChildren node =
seq { yield node
for child in getChildren node do
yield! getDescendants getChildren child }
let isLeaf getChildren node = Seq.isEmpty (getChildren node)
let getLeaves getChildren node = getDescendants getChildren node
|> Seq.filter (isLeaf getChildren)
As you can see, all functions have a getChildren
argument, which is a function that
enumerates the children of a node of a given type.
The second module handles the more specific case of XML trees:
module XmlTree
open System.Xml.Linq
let getXmlChildren (node : XElement) = node.Elements()
let getDescendants = Tree.getDescendants getXmlChildren
let getLeaves = Tree.getLeaves getXmlChildren
let isLeaf = Tree.isLeaf getXmlChildren
A specific getXmlChildren
function for XML nodes is defined and passed to
the curried Tree
functions.
Now there is an awful lot of code duplication.
Is it somehow possible to do the following? (pseudocode)
module XmlTree = Tree with getChildren = fun (node : XElement) -> node.Elements()