여기에 gen-class
을 사용하는 방법이 있습니다. 나는 단위를 확인하고 정규화하기위한 함수를 조롱했다. 구현 된 유일한 작업은 *
이며 force
에서 사용됩니다. 코드가 당신은 당신의 leiningen 프로젝트 폴더의 src
폴더에 big_decimal_meta.clj
라는 파일에 다음 코드를 저장하고로드해야합니다 compile
gen-class
을 사용하고 있기 때문에
주의하시기 바랍니다.
BigDecimalMeta
gen-class
를 사용하여 :
(ns big-decimal-meta
(:refer-clojure :exclude [* force])
(:gen-class
:name BigDecimalMeta
:extends java.math.BigDecimal
:state metadata
:init init
:implements [clojure.lang.IObj]))
(defn -init [& args]
[args (atom nil)])
(defn -withMeta [this metadata]
(reset! (.metadata this) metadata)
this)
(defn -meta [this]
(deref (.metadata this)))
(compile 'big-decimal-meta)
*
및 force
기능을 몇 가지 예제 코드 :
(def x (with-meta (BigDecimalMeta. 1) {:unit :kg}))
(def y (with-meta (BigDecimalMeta. 3.5) {:unit :mss}))
(def z (with-meta (BigDecimalMeta. 4.5) {:unit :V}))
(defn unit [x]
(-> x meta :unit))
(defn * [x y]
(BigDecimalMeta. (str (.multiply x y))))
(defn mass? [x]
(#{:kg :gr :mg ,,,} (unit x)))
(defn accel? [x]
(#{:mss ,,,} (unit x)))
(defn to-kg [x] x)
(defn to-mss [x] x)
(defn force [mass accel]
(assert (mass? mass))
(assert (accel? accel))
(let [mass (to-kg mass)
accel (to-mss accel)]
(with-meta (* mass accel) {:unit :N})))
(println (force x y) (meta (force x y)))
(println (force x z) (meta (force x z)))
'java.lang.Long' 및 친구들이'final'이므로'java.math.BigDecimal' 옵션을 사용하고 있습니까? 그렇다면 그것을 확장하고'clojure.lang.IObj'를 구현할 수 있습니다. –
어떤 방법으로 확장해야합니까? deftype/gen-class/reify? 작은 모범을 보여 주실 수 있습니까? –
방금 일부 코드와 함께 답변을 추가했습니다. 나는 그것을 구현하는 방법에 대해 궁금해서 정말 작은 예제는 아닙니다. P. 희망이 도움이됩니다. –