为什么Clojure的多方法比'if'或'case'语句更好 [英] Why are Clojure's multimethods better than 'if' or 'case' statements

查看:274
本文介绍了为什么Clojure的多方法比'if'或'case'语句更好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一些时间,试图理解Clojure多方法。根据我的理解,主要的pro多方法参数是它们的灵活性,然而,我对为什么多方法比一个简单的if或case语句更好的论证感到困惑。有人可以请解释一下,多态性和过度夸大的案例语句之间的界限是什么?

I've spent some time, trying to understand Clojure multimethods. The main "pro" multimethod argument, as far as I understand, is their flexibility, however, I'm confused with the argumentation of why multimethods are better than a simple if or case statement. Could someone, please, explain, where is the line between polymorphism and an overglorified case statement drawn?

编辑:我应该在问题中更清楚,更感兴趣的是与'if'语句的比较。非常感谢您的答案!

I should have been clearer in the question, that I'm more interested in comparison with the 'if' statement. Thanks a lot for the answers!

推荐答案

多方法和一个大的if语句之间的区别是,你需要修改函数包含将case添加到if语句的case语句。您可以添加一个新方法,而无需触摸之前存在的方法。

The difference between multimethods and a big if-statement is that you need to modify the function that contains the case-statement to add cases to the if-statement. You can add a new method without touching the previously existing methods.

因此,如果您在库中定义一个multimethod,并且希望您的用户能够扩展它自己的数据类型,这没有问题。如果你使用if语句,这将是一个大问题。

So if you define a multimethod inside your library and you want your users to be able to extend it for their own data types, that's no problem. If you had used an if-statement instead, it would be a big problem.

这篇关于为什么Clojure的多方法比'if'或'case'语句更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆