是否可以将参数传递给F#模块? [英] Is it possible to pass parameters to F# modules?
问题描述
我是F#的新手,正在学习基础知识.
I'm new to F# and learning the basics.
我有两个模块.一种通用的树数据结构,称为Tree
:
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)
如您所见,所有函数都有一个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.
第二个模块处理XML树的更具体情况:
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
已定义XML节点的特定getXmlChildren
函数并将其传递给
咖喱的Tree
函数.
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()
推荐答案
F# doesn't support functors so you cannot pass parameters to F# modules. In your example, passing a function which generates children of a node to object constructors is enough:
type Tree<'T>(childFn: 'T -> 'T seq) =
let getChildren = childFn
member x.getDescendants node =
seq { yield node
for child in getChildren node do
yield! x.getDescendants child }
member x.isLeaf node = node |> getChildren |> Seq.isEmpty
member x.getLeaves node = node |> x.getDescendants |> Seq.filter x.isLeaf
// Type usage
open System.Xml.Linq
let xmlTree = new Tree<XElement>(fun x -> x.Elements())
对于更复杂的情况,继承 .特别是,您可以将Tree<'T>
声明为具有抽象成员getChildren
的抽象类,并在XmlTree
子类中覆盖该方法.
For more sophisticated cases, inheritance is the way to go. Particularly, you can declare Tree<'T>
as an abstract class with abstract member getChildren
, and override that method in XmlTree
subclass.
这篇关于是否可以将参数传递给F#模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!