自递归 clojure 多重方法对于嵌套分类问题来说是一个好的设计吗?
我有大量的数据地图序列,每个地图都需要以嵌套方式进行分类。
即给定的项目可能是A或B(由函数确定),如果它是B则它可能是C或D(由另一个函数确定),依此类推。在每个阶段,可以将与分类相关的更多数据添加到每个地图。进行分类的函数本身非常复杂,可能需要引入额外的数据才能做出决定。
自递归多方法是否是构建代码以实现此目的的好方法?我会分派迄今为止为某个项目确定的最具体的类型,或者在无能为力时返回当前最佳分类。
我可以在单个分类函数中使用嵌套的 if 来获得所需的效果,但天哪,太丑了。
多重方法是否适合这里,或者我是否使事情过于复杂并且缺少构建代码的更简单的方法?
I have a large sequence of data-maps and each map needs to be classified in a nested fashion.
i.e. a given item may be an A or a B (as determined by a function), if it is a B then it may be a C or a D (determined by another function) and so on down. At each stage more data relating to the classification may be added to each map. The functions to do the classification are themselves quite complex and may need to bring in additional data to make the determinations.
Would a self-recursive multimethod be a good way to structure the code to do this? I would dispatch on the most specific type so far determined for an item, or return the best current classification when nothing further can be done.
I could get the desired effect with nested ifs inside a single classification function but gosh is that ugly.
Is a multimethod a good fit here or am I over-complicating things and missing a simpler way of structuring the code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看来多种方法在这里可能有用。我猜所有的复杂性都在调度函数中?因此,一旦您对顶层进行分类,您就会再次使用触发不同实例的更多信息来触发多方法?
另一种思考方式是基于遍历决策树而不是遍历输入。我想知道使用 clojure.zip 遍历分类函数树是否是一个有趣的解决方案。每个节点的分类函数可以告诉您下一步如何遍历树(转到哪个子节点)。您不一定需要 clojure.zip,但它已经包含树导航。
Seems like multimethods might be useful here. I guess all the complexity is in the dispatch function? So once you classify the top level you fire the multimethod again with more info that triggers a different instance?
Another way to think this is to base it around traversing the decision tree instead of traversing your input. I wonder whether using clojure.zip to traverse a tree of classification functions might be an interesting solution. Your classification function at each node could tell you how to next traverse the tree (which child to go to). You wouldn't need clojure.zip necessarily but it has the tree navigation in it already.
多方法很棒,因为当问题的复杂性需要时,它们允许这种级别的调度。我说如果它能达到你想要的效果就去吧。
也许您可以构建一个
isa
层次结构来帮助multimethods are great because they allow this level of dispatch when the complexity of the problem calls for it. I say go for it if it does what you want.
Perhaps you could build an
isa
hierarchy to help