旧行李 2009-10-06 19:20 采纳率: 25%
浏览 215
已采纳

为什么 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.

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

转载于:https://stackoverflow.com/questions/1527548/why-does-clojure-have-keywords-in-addition-to-symbols

  • 写回答

5条回答 默认 最新

  • 北城已荒凉 2009-10-06 19:52
    关注

    Here's the Clojure documentation for Keywords and Symbols.

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

    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).

    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 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. Keywords in Clojure are not Symbols.

      user> (symbol? :foo)  
      false
      
    2. Keywords don't belong to any namespace unless you specifically qualify them:

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画