为什么Clojure有“关键字"?除了“符号"? [英] Why does Clojure have "keywords" in addition to "symbols"?

查看:21
本文介绍了为什么Clojure有“关键字"?除了“符号"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对其他 Lisps(尤其是 Scheme)有一定的了解.最近我一直在阅读 Clojure.我看到它同时具有符号"和关键字".我熟悉的符号,但不熟悉关键字.

I have a passing knowledge of other Lisps (particularly Scheme) from way back. Recently I've been reading about Clojure. I see that it has both "symbols" and "keywords". Symbols I'm familiar with, but not with keywords.

其他 Lisp 有关键字吗?除了具有不同的符号(即:冒号)之外,关键字与符号有何不同?

Do other Lisps have keywords? How are keywords different from symbols other than having different notation (ie: colons)?

推荐答案

这里是 Clojure 文档用于关键字和符号.

Here's the Clojure documentation for Keywords and Symbols.

关键字是对自身求值的符号标识符.它们提供了非常快速的相等性测试...

Keywords are symbolic identifiers that evaluate to themselves. They provide very fast equality tests...

符号是通常用来指代其他事物的标识符.它们可以在程序形式中用于引用函数参数、let 绑定、类名和全局变量...

Symbols are identifiers that are normally used to refer to something else. They can be used in program forms to refer to function parameters, let bindings, class names and global vars...

关键字通常用作轻量级的常量字符串",例如用于哈希映射的键或多方法的调度值.符号通常用于命名变量和函数,除宏等外,将它们直接作为对象进行操作的情况较少见.但是没有什么可以阻止您在任何使用关键字的地方使用符号(如果您不介意一直引用它们).

Keywords are generally used as lightweight "constant strings", e.g. for the keys of a hash-map or the dispatch values of a multimethod. Symbols are generally used to name variable and functions and it's less common to manipulate them as objects directly except in macros and such. But there's nothing stopping you from using a symbol everywhere you use a keyword (if you don't mind quoting them all the time).

查看差异的最简单方法是阅读 Clojure 源代码中的 Keyword.javaSymbol.java.有一些明显的实现差异.例如,Clojure 中的 Symbol 可以有元数据,而 Keyword 则不能.

The easiest way to see the difference is to read Keyword.java and Symbol.java in the Clojure source. There are a few obvious implementation differences. For example a Symbol in Clojure can have metadata and a Keyword can't.

除了单冒号语法之外,您还可以使用双冒号来制作命名空间限定的关键字.

In addition to single-colon syntax, you can use a double-colon to make a namespace-qualified keyword.

user> :foo
:foo
user> ::foo
:user/foo

Common Lisp 有关键字,Ruby 和其他语言也是如此.当然,它们在这些语言中略有不同.Common Lisp 关键字和 Clojure 关键字之间的一些区别:

Common Lisp has keywords, as do Ruby and other languages. They are slightly different in those languages of course. Some differences between Common Lisp keywords and Clojure keywords:

  1. Clojure 中的关键字不是符号.

  1. Keywords in Clojure are not Symbols.

user> (symbol? :foo)  
false

  • 关键字不属于任何命名空间,除非您特别限定它们:

  • Keywords don't belong to any namespace unless you specifically qualify them:

    user> (namespace :foo)
    nil
    user> (namespace ::foo)
    "user"
    

  • (感谢 Rainer Joswig 给我一些值得关注的想法.)

    (Thanks Rainer Joswig for giving me ideas of things to look at.)

    这篇关于为什么Clojure有“关键字"?除了“符号"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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