`
yangdong
  • 浏览: 65089 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

封闭空间

 
阅读更多
《Structure and Interpretation of Computer Programs》中提到,“The ability to create pairs whose elements are pairs is the essence of list structure's importance as a representational tool. We refer to this ability as the closure property of cons.”这话表面上是说 cons 作为 LISP 的核心,能够把自己产生的 pair 作为 cons 的参数进而去产生新的组合 pair,是列表数据结构在表示上非常本质的东西。“closure property”我倾向于翻译成封闭性。因为在代数中,给定 f(x) = y,如果任意 x 属于 Z,且 y 也属于 Z,那么 Z 就对 f 是封闭的。

当然我们可以很容易地想到高中数学里面的列表。这跟 LISP 中的列表是完全对应的。正是这种特性造就了 LISP 语言的强大。但是这种模式对于即使不熟悉数学的程序员来说也应该似曾相识。比如 JUnit4 和 JMock 里面用的 Hamcrest Matcher。你可以任意组合各种 matcher 达到想要的效果。比如 assertThat(result, is(not(greaterThan(10)))。它使得 JUnit 摆脱了不停地往 Assert 类里面增加方法的局面。也是为什么 JUnit4 要绑定 Hamcrest Matcher 发布的原因。如今你很难看到一个优秀的测试框架里面不用 Hamcrest Matcher 的。Matcher 的模式就是:makeMatcher(someMather) === AnotherMatcher。也就是说,从逻辑上,makeMatcher 和 Matcher 这个抽象集合组成了一个代数空间。

找到这样的空间,我们就可能找到了非常强大而优雅的工具。比如 SICP 里面提到的 painter。我们可以生成一个给定 painter 的水平镜像 painter、垂直镜像 painter、扭曲 painter,等等。这点对于我们做面向对象设计的时候也极有启发价值。

=== Update ===

Monads 跟封闭空间也很相似。参考:Monads Are Not Metaphors
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics