gpt4 book ai didi

clojure - 如何向该函数添加参数?

转载 作者:行者123 更新时间:2023-12-02 18:37:42 25 4
gpt4 key购买 nike

我想要这个功能

(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))))

能够有两个参数签名。该示例显示了 str-1 str-2 和 len (固定长度)。这样做是为了,如果字符串小于固定默认值(例如 15),将返回一个长度值,而不会导致溢出异常。

我希望能够仅传递 str-1 和 len,而不传递 str-2,但我不太确定该怎么做。

我知道如果未传入 l2,代码将必须更改。我想知道如何设置参数。任何例子将不胜感激。

谢谢。

最佳答案

defn 有两种语法

(defn foo [] (expression) (expression))

(defn foo
([] (exp1) (exp2)) ; arity 0
([x] (exp1) (exp2)) ;arity 1
([x y] (exp1) (exp2)) ; arity 2
<小时/>

一种常见的模式是让较少数量的版本填充默认值并调用较高数量的情况:

(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)))))

<小时/>附带说明一下,您可以使用可变数量的参数编写一个非常相似的函数:

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

关于clojure - 如何向该函数添加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11144426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com