gpt4 book ai didi

clojure - Clojure 中的类型系统

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

Clojure 中的“抽象编程”原则与鸭子类型(duck typing)相同吗?如果不是,有什么区别?

这里引用 http://www.braveclojure.com/core-functions-in-depth/ :

The reason is that Clojure defines map and reduce functions in terms of the sequence abstraction, not in terms of specific data structures. As long as a data structure responds to the core sequence operations (the functions first, rest, and cons, which we’ll look at more closely in a moment), it will work with map, reduce, and oodles of other sequence functions for free. This is what Clojurists mean by programming to abstractions, and it’s a central tenet of Clojure philosophy.

I think of abstractions as named collections of operations. If you can perform all of an abstraction’s operations on an object, then that object is an instance of the abstraction. I think this way even outside of programming. For example, the battery abstraction includes the operation “connect a conducting medium to its anode and cathode,” and the operation’s output is electrical current. It doesn’t matter if the battery is made out of lithium or out of potatoes. It’s a battery as long as it responds to the set of operations that define battery.

数据类型通过行为(“响应”)被识别为抽象类的一部分。这不就是鸭子类型(duck typing)的本质吗?感谢您的意见。

最佳答案

Data types are identified to be part of the abstract class by behaviour ("responds to").

但事实并非如此。在 JVM 上,如果类型明确声明它们实现了接口(interface),然后实现了其方法,那么它们只能是接口(interface)的一部分。仅仅实现适当命名的方法是不够的,就像在 Python(一种典型的鸭子类型(duck typing)语言)中一样。

所写的内容并不完全错误,但需要一些特定的观点才能将其解释为正确:你必须意识到,当作者写作时,

As long as a data structure responds to the core sequence operations...

这意味着该类型必须实现核心序列接口(interface)及其方法。在某种程度上,仅公开名为 first 的函数不足以“响应”同名的核心序列操作:该类型还必须实现正确的接口(interface)才能回复”。在虚拟机中编写内容是一种奇怪的方式,它不以响应消息为框架,并且需要一些专业知识和眯眼才能找到正确的含义,但对于初学者来说这是一个合理的简化,他们不需要了解尚未详细说明...除非他们倾向于向 Stack Overflow 询问有关鸭子类型(duck typing)的问题!

关于clojure - Clojure 中的类型系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43840366/

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