gpt4 book ai didi

parameters - 是否可以将参数传递给 F# 模块?

转载 作者:行者123 更新时间:2023-12-04 22:06:56 24 4
gpt4 key购买 nike

我是 F# 新手,正在学习基础知识。

我有两个模块。一种通用的树数据结构,称为 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参数,这是一个函数
枚举给定类型的节点的子节点。

第二个模块处理 XML 树的更具体的情况:
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

具体 getXmlChildren XML 节点的函数被定义并传递给
curry Tree职能。

现在有大量的代码重复。

有没有可能做以下事情? (伪代码)
module XmlTree = Tree with getChildren = fun (node : XElement) -> node.Elements()

最佳答案

F# 不支持 functors所以你不能将参数传递给 F# 模块。在您的示例中,将生成节点子节点的函数传递给对象构造函数就足够了:

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())

对于更复杂的案例, inheritance是要走的路。特别是可以声明 Tree<'T>作为具有抽象成员的抽象类 getChildren , 并在 XmlTree 中覆盖该方法子类。

关于parameters - 是否可以将参数传递给 F# 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10580854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com