简体   繁体   English

Clojure设定字串值

[英]Clojure set string value

I have a variable "testtext". 我有一个变量“ testtext”。 Depending on a other variable "testvalue", thats always the value 1 or 2, it needs to be set to something. 根据其他变量“ testvalue”,多数民众赞成总是值1或2,它需要设置为某种东西。 So if testvalue is 1, i need to set testtext to "its one". 因此,如果testvalue为1,我需要将testtext设置为“它的一个”。 And when testvalue is 2, i need to set testtext to "its two". 当testvalue为2时,我需要将testtext设置为“它的两个”。 Right now i have: 现在我有:

 (cond
        (= testvalue 1) (var-set testtext "its one")
        (= testvalue 2) (var-set testtext "its two")
        :else (var-set testtext "ERROR")
        )

But i get the error "String cannot be cast to clojure.lang.Var" So my question is, how do i properly set a string value, assuming that's what I did wrong. 但是我收到错误消息“无法将字符串强制转换为clojure.lang.Var”,所以我的问题是,假设这是我做错的事情,如何正确设置字符串值。

You want something more like this: 您想要更多类似这样的东西:

 (let [result (cond
                (= testvalue 1) "its one"
                (= testvalue 2) "its two"
                :else "ERROR"  ) ]
   (println "result:" result))

Using var-set is very rare in Clojure. Clojure中很少使用var-set I can't answer in too much more detail without knowing your exact use-case. 在不知道您确切的用例的情况下,我无法提供更多详细信息。

If you really need something like a Java variable, you could use a Clojure atom : 如果您确实需要Java变量之类的东西,则可以使用Clojure atom

 (def result (atom nil))
 (cond
   (= testvalue 1) (reset! result "its one")
   (= testvalue 2) (reset! result "its two")
   :else (reset! result "ERROR" ))
 (println "result:" @result))

You probably want something like: 您可能想要类似的东西:

(defn func 
  [test-value]
  (let [test-var (cond
                 (= test-value 1) "it's one"
                 (= test-value 2) "it's two"
                 :else "ERROR")]
    test-var))
=> #'user/func
(func 1)
=> "it's one"
(func 2)
=> "it's two"
(func 3)
=> "ERROR"

The let form let's you assign values to vars. let表单让您为vars分配值。 Sticking it in a function is a convenient way to return the result. 将其粘贴在函数中是返回结果的便捷方法。

On most contexts you don't want to modify an existing "variable's" value, instead you use let to bind a value to a symbol. 在大多数情况下,您不想修改现有的“变量”值,而是使用let将值绑定到符号。 It would be easier to answer if we knew the bigger picture, but as already mentioned atom is a datatype to which you can atomically swap in a new value. 如果我们知道更大的范围,则回答起来会更容易,但是正如已经提到的, atom是一种数据类型,您可以原子地交换新值。

I'd say this is more idiomatic, although not quite what you asked: 我想说这是比较惯用的,尽管与您要求的不完全相同:

(def lookup-table
  {1 "its one"
   2 "its two"})

(defn make-lookup [i]
  (get lookup-table i "ERROR"))

(doseq [i (range 4)]
  (println i "=" (make-lookup i)))

Prints: 印刷品:

0 = ERROR
1 = its one
2 = its two
3 = ERROR

Instead of thinking how to assign a value to a variable, you should think what do you want to use that value for. 与其考虑如何为变量分配值,不如考虑使用该值的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM