2013-04-14 52 views
1

我是Clojure的新手,所以我想知道是否有人可以向我解释我要出错的地方。我正在解决4Clojure中的一些问题以熟悉,其中之一是计算可变参数的最大值,,而不使用Clojure的内置最大函数。我应该填空:计算可变数量参数的最大值

(_ 1 8 3 4) 

这样的结果是4

为此,我想实现可变参数数量的函数。由于Lisp中的所有内容都必须是递归的,因此我的基本情况是只有一个元素,在这种情况下,max是元素本身。否则,我比较第一和第二个元素,并递归调用函数在适当的情况下:

(fn max-of 
    ; base case, only one element, return the element 
    ([x] x) 
    ; if more than one element... 
    ([x & more] 
     ; ...compare the first element and the second 
     ; if the first element is bigger than the second 
     ; drop the second element, else drop the first 
     (if (> x (first more)) (max-of (cons x (rest more))) 
           (max-of more)))) 

但是这给了我:

user=>  ((fn max-of 
#_=>   ([x] x) 
#_=>   ([x & more] 
#_=>    (if (> x (first more)) (max-of (cons x (rest more))) 
#_=>         (max-of more)))) 
#_=>  1 8 3 4) 
(8 3 4) 

而且我不知道为什么这将返回我的列表而不是在所述列表上调用我的函数。

回答

1

因为你传递一个列表作为单个实体的第一个递归调用,见

(max-of 8 3 4)(max-of '(8 3 4))的区别

您可以使用apply来缓解这个问题:

(apply max-of (cons x (rest more)))