2014-11-04 65 views
0

我有以下Clojure的包裝與宏觀參數1:如何向Clojure中的宏添加第二個參數?

(defmacro with-init-check 
"Wraps the given statements with an init check." 
[body] 
`(if (initialized?) 
    ~body 
    (throw (IllegalStateException. "GeoIP db not initialized.")))) 

我想補充ip-version到它,所以我可以檢查,如果只是:IPv6:IPv4被初始化。但是參數不獲得通過,通過的時候我試試這個:

(defmacro with-init-check 
    "Wraps the given statements with an init check." 
    [ip-version body] 
    `(if (initialized? ip-version) 
    ~body 
    (throw (IllegalStateException. "GeoIP db not initialized.")))) 

當我使用它像這樣,我得到「沒有這樣的變種」的「如果 - 讓[位置...」行:

(defn- lookup-location 
    "Looks up IP location information." 
    [ip ip-version] 
    (with-init-check ip-version 
    (if-let [location (get-location ip ip-version)] 
    {:ip ip 
    :countryCode (.countryCode location) 
    :countryName (.countryName location) 
    :region (.region location) 
    :city (.city location) 
    :postalCode (.postalCode location) 
    :latitude (.latitude location) 
    :longitude (.longitude location) 
    :dma-code (.dma_code location) 
    :area-code (.area_code location) 
    :metro-code (.metro_code location)}))) 

如何獲得ip-versioninitialized?函數?

+0

下面的代碼在線,所以你可以看到上下文: https://github.com/sventech/clj-geoip/commit/e4a9a2c4801b13143ea7f3270232d03eb419308d – sventechie 2014-11-04 14:49:16

回答

4

引文結束它與~

(defmacro with-init-check 
    "Wraps the given statements with an init check." 
    [ip-version body] 
    `(if (initialized? ~ip-version) ; unquoted with ~ 
    ~body 
    (throw (IllegalStateException. "GeoIP db not initialized.")))) 

從您的文檔字符串推導,你可能還需要允許多表達體,並在do表達所享有,它們接起來:

(defmacro with-init-check 
    "Wraps the given statements with an init check." 
    [ip-version & body] ; multi-expression bodies with & 
    `(if (initialized? ~ip-version) 
    (do [email protected]) ; unquote-spliced with [email protected] 
    (throw (IllegalStateException. "GeoIP db not initialized."))))