Clojure 如何将算术添加到此函数?
我想要这个函数Clojure 如何将算术添加到此函数?,clojure,Clojure,我想要这个函数 (defn ret-lowest-str-len "Computes the lengths of two strings. Returns default length -- len -- if len is <= the length of str-1 and len is <= length of str-2. Else, returns smaller of length of str-1 and str-2." [s
(defn ret-lowest-str-len
"Computes the lengths of two strings. Returns default length -- len --
if len is <= the length of str-1 and len is <= length of str-2.
Else, returns smaller of length of str-1 and str-2."
[str-1 str-2 len]
(let [l1 (count str-1)
l2 (count str-2)]
(if (and (<= len l1) (<= len l2))
len
(if (< l1 l2)
l1
l2))))
(定义最低结构长度)
“计算两个字符串的长度。返回默认长度--len--
如果lendefn有两个语法
(defn foo [] (expression) (expression))
及
一种常见的模式是让较小的arity版本填写默认值,并调用较高的arity情况:
(defn ret-lowest-str-len
([str-1 len] (ret-lowest-str-len str-1 "" len))
([str-1 str-2 len]
(let [l1 (count str-1)
l2 (count str-2)]
(if (and (<= len l1) (<= len l2))
len
(if (< l1 l2)
l1
l2)))))
我将更进一步,使用可选参数列表的&
语法,使其适用于任意数量的字符串,使用以下内容:
(defn lowest-str-len [default-len & strs]
(let [lens (map count strs)]
(apply min default-len lens)))
谢谢@Arthur。我去看看这个。效果很好@Arthur Ulfeldt。
user> (defn ret-lowest-str-len [& args] (reduce min (map count args)))
#'user/ret-lowest-str-len
user> (ret-lowest-str-len "a" "aaaa" "aaaaaaaaa")
1
(defn lowest-str-len [default-len & strs]
(let [lens (map count strs)]
(apply min default-len lens)))