让vs def in clojure [英] let vs def in clojure

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

问题描述

我想在clojure程序中创建一个Java Scanner类的本地实例。为什么这不工作:

 ;给我:count不支持此类型:Symbol 
new Scannerabc))

但它会让我创建一个全局实例: p>

 (def s(new Scannerabc))

我的印象是,唯一的区别是范围,但显然不是。

问题是你使用 let

code>是错误的。



让这样工作:

 (let [identifier(expr)])

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

 (let [s(Scanner。abc)] 
(exprs))

您只能在let的范围内使用let做的词法绑定(开头和结尾括号)。让我们只创建一组词法绑定。我使用def做一个全局绑定,让我绑定的东西,我只想在let的范围内,因为它保持清洁。他们都有自己的用途。



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


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

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

解决方案

The problem is that your use of let is wrong.

Let works like this:

(let [identifier (expr)])

So your example should be something like this:

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

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.

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

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

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