我在Clojure中使用deftype时遇到了问题.如果我运行以下代码:
(defprotocol TestProt
(geta [this])
(getb [this]))
(deftype TestType [a b]
TestProt
(geta [this] a)
(getb [this] b))
(defn test-function [^TestType a-testtype]
(print (.geta a-testtype)))
(def test-tt (TestType. 1 1))
(test-function test-tt)
Run Code Online (Sandbox Code Playgroud)
然后编译器抛出:ClassCastException MyProject.core.TestType无法强制转换为MyProject.core.TestType.我做错了什么,或者这是一个错误?请注意,如果我从test-function中删除类型注释,那么它只是:
(defn test-function [a-testtype]
(print (.geta a-testtype)))
Run Code Online (Sandbox Code Playgroud)
然后代码工作正常,但我得到一个关于反射的警告(启用了反射警告),并且它运行得更慢,这违背了在我当前用例中使用deftype的目的.
编辑:好的,代码在repl中工作,但是当我使用ctrl-alt-s加载它时(我在Eclipse中通过逆时针运行它).所以问题似乎是Eclipse或逆时针.
例如:
class Person {
String name;
}
Run Code Online (Sandbox Code Playgroud)
我想{:name "xxx}从Person的实例中获取.
我知道(from_json (.toJson person))可以做到.
有没有更好的方法来实现它?
这是一个非常简单的Leiningen项目示例lein new app hanging,仅使用两个文件project.clj:
(defproject hanging "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.6.0"]]
:main hanging.core
:aot [hanging.core]
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
Run Code Online (Sandbox Code Playgroud)
并且src/hanging/core.clj:
(ns hanging.core (:gen-class))
(println "1")
(def problematic (future))
(println "2")
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println 3))
Run Code Online (Sandbox Code Playgroud)
在运行项目时,这是输出(提示冻结,我必须用Cc杀死它):
% lein clean && lein run
Compiling hanging.core
1
2
Run Code Online (Sandbox Code Playgroud)
注释掉problematicVar定义后,这是输出(JVM关闭):
% lein clean && lein run
Compiling hanging.core
1
2
1
2
3
Run Code Online (Sandbox Code Playgroud)
我猜AOT是罪魁祸首,但有人可以解释一下究竟发生了什么吗?
我对第二个(注释)版本没有问题:在AOT期间,编译器执行所有顶级表单,这就是输出中看到两次1和2的原因. …
假设我有以下字符串:
(def strg "apple orange apple")
Run Code Online (Sandbox Code Playgroud)
我想要字符串中每个非唯一单词的边界索引.因此苹果的第一次出现应该具有边界指数(0,4),而苹果的第二次出现应该具有边界指数(13,17).
我一直在玩的一种方法是首先在字符串中存储每个字符的索引,然后,对于每个索引n,通过在n-1处查找空格来识别字边界(是的,这错过了开头的 - -string words).如果满足此条件,则迭代下一个k个字符,直到另一个空格被击中---紧邻该空格之前的位置处的字符是第二个边界索引.这个(失败的)代码的第一部分是
(for [ch strg]
(let [indx (int (.indexOf strg (str ch)))]
(cond (= (subs ch indx-1 ) " " )
continue with rest of above-described code logic
Run Code Online (Sandbox Code Playgroud)
任何想法(Clojure,Java或Python都很好)将不胜感激