clojure 中的 let vs def [英] let vs def in clojure

查看:29
本文介绍了clojure 中的 let vs def的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 clojure 程序中创建 Java Scanner 类的本地实例.为什么这不起作用:

I want to make a local instance of a Java Scanner class in a clojure program. Why does this not work:

; gives me:  count not supported on this type: Symbol 
(let s (new Scanner "a b c"))

但它会让我创建一个这样的全局实例:

but it will let me create a global instance like this:

(def s (new Scanner "a b c"))

我的印象是唯一的区别是范围,但显然不是.letdef 有什么区别?

I was under the impression that the only difference was scope, but apparently not. What is the difference between let and def?

推荐答案

问题是你的let使用方法不对.

The problem is that your use of let is wrong.

let 是这样工作的:

(let [identifier (expr)])

所以你的例子应该是这样的:

So your example should be something like this:

(let [s (Scanner. "a b c")]
  (exprs))

您只能在 let 的范围内(开始和结束括号)使用由 let 进行的词法绑定.让我们创建一组词法绑定.我使用 def 进行全局绑定,并使用 let 来绑定我只在 let 范围内想要的东西,因为它使事情保持干净.它们各有用途.

You can only use the lexical bindings made with let within the scope of let (the opening and closing parens). Let just creates a set of lexical bindings. I use def for making a global binding and lets for binding something I want only in the scope of the let as it keeps things clean. They both have their uses.

注意:(Class.) 与 (new Class) 相同,只是语法糖.

NOTE: (Class.) is the same as (new Class), it's just syntactic sugar.

这篇关于clojure 中的 let vs def的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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