【问题标题】:how would a 'construct' function be implemented in clojure?如何在 clojure 中实现“构造”函数?
【发布时间】:2013-04-29 01:26:10
【问题描述】:

从这个问题跟进:how to get the constructor of a class that contains a primitive in clojure?

我知道我可以编写一个只在类名末尾添加. 的宏,但我希望有一个函数可以做到这一点:

(defn construct [cl & args]
   ....... )

(construct "java.util.Date" 0) 
;=> #inst "1970-01-01T00:00:00.000-00:00"

(construct "java.util.Date" 2013 4 27) 
;=> #inst "2013-04-26T14:00:00.000-00:00"

(construct "java.util.Date" "27 Apr 2013") 
;=> #inst "2013-04-26T14:00:00.000-00:00"

函数如何检查原始类型?

【问题讨论】:

  • 在你的函数体中添加条件逻辑。标准 Clojure 没有 Java 那样的重载和类型。
  • 是的,尽管您可以使用 defn 的多体形式来重载 arity
  • 那么java互操作是怎么做的呢?
  • introp 运算符点 (.) 是编译器中特定支持的特殊运算符,但 Clojure 函数定义不支持类型重载。为此,您可以使用多方法或协议。
  • 或许类似的解决方案就足够了:stackoverflow.com/questions/3748559/…

标签: clojure


【解决方案1】:

new怎么样

例子:

(new java.util.Date 0)
 => #inst "1970-01-01T00:00:00.000-00:00"

(new java.util.Date "27 Apr 2013")
=> #inst "2013-04-26T22:00:00.000-00:00"

【讨论】:

  • 您只是将 new 别名为构造。任何你可以使用该构造的地方,你都可以使用 new 并添加好。
  • “新”宏的源文件在哪里?
猜你喜欢
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多