使用带字符串的加号和加法操作数Clojure
有没有办法在Clojure中将使用带字符串的加号和加法操作数Clojure,clojure,Clojure,有没有办法在Clojure中将*和+操作数与字符串一起使用 例如: (defn times [a b] (* a b)) => (times x y) Desired Output: x*y 或 我假设您正在JVM上使用Clojure 函数*仅适用于数字。 通过将字符串解析为正确的类型,可以将其转换为数字: (def int1 (Integer/parseInt "1")) (def double1 (Double/parseDouble "1.0")) (def product1 (
*
和+
操作数与字符串一起使用
例如:
(defn times [a b] (* a b))
=> (times x y)
Desired Output: x*y
或
我假设您正在JVM上使用Clojure 函数
*
仅适用于数字。
通过将字符串解析为正确的类型,可以将其转换为数字:
(def int1 (Integer/parseInt "1"))
(def double1 (Double/parseDouble "1.0"))
(def product1 (* int1 double1)) ;; 2.0
;; or
(def int2 (clojure.edn/read-string "1"))
(def double2 (clojure.edn/read-string "1.0"))
(def product2 (* int2 double2)) ;; 2.0
我假设您正在JVM上使用Clojure 函数
*
仅适用于数字。
通过将字符串解析为正确的类型,可以将其转换为数字:
(def int1 (Integer/parseInt "1"))
(def double1 (Double/parseDouble "1.0"))
(def product1 (* int1 double1)) ;; 2.0
;; or
(def int2 (clojure.edn/read-string "1"))
(def double2 (clojure.edn/read-string "1.0"))
(def product2 (* int2 double2)) ;; 2.0
我看不出有什么问题:
(defn * [a b]
(if (and (string? a) (string? b))
(str a b)
(clojure.core/* a b)))
WARNING: * already refers to: #'clojure.core/* in namespace: user, being replaced by: #'user/*
=> #'user/*
(* 4 5)
=> 20
(* "A" "B")
=> "AB"
我看不出有什么问题:
(defn * [a b]
(if (and (string? a) (string? b))
(str a b)
(clojure.core/* a b)))
WARNING: * already refers to: #'clojure.core/* in namespace: user, being replaced by: #'user/*
=> #'user/*
(* 4 5)
=> 20
(* "A" "B")
=> "AB"
为什么
(defn*[AB](str a b))
不起作用?我得到的错误基本上是说变量不能被转换成数字。其他语言将这种行为定义为3*'AB'=>'abababab'
,但必须要将两个字符串相乘。我很高兴,Clojure没有想出什么办法。只需自己定义该功能即可。另外,str
您预期的+
会发生什么(我假设)为什么(defn*[AB](str AB))
不起作用?我得到的错误基本上是说变量不能转换成数字。其他语言将该行为定义为3*'AB'=>ababababab'
,但是将两个字符串相乘是你必须想到的。我很高兴,Clojure没有想出什么办法。只需自己定义该功能即可。另外,str
实现了您对+
的期望(我想)非常感谢。非常感谢。非常感谢。没问题。如果您喜欢,请向上投票,如果答案回答您的问题,请单击勾号。非常感谢。没问题。如果您喜欢,请向上投票,如果答案回答了您的问题,请单击勾号。