Defining my own max function with variable arguments

I am studying Clojure solving the problems listed in 4clojure . One exercise is to create your own function maxwith variable arguments.

I am trying to solve this simple problem using REPL and I got to this solution:

(defn my-max 
    [first & more] (calc-max first more))

(defn calc-max 
    [m x] 
        (cond (empty? x) m
            (> (first x) m) (calc-max (first x) (rest x))
            :else calc-max m (rest x)))

Which works fine, but the exercise does not allow use def, and so I have to flip both functions into one. When I replace the link calc-maxwith my code, the result is:

(defn my-max 
    [first & more] 
    ((fn calc-max 
        [m x] 
            (cond (empty? x) m
                (> (first x) m) (calc-max (first x) (rest x))
                :else calc-max m (rest x)))
                    first more))

But this code does not work and returns the following error:

user=> (my-max 12 3 4 5 612 3)
java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)

I assume that this error is due to an attempt to evaluate the result of the function calc-max, and I assume that this is a syntax error on my part, but I cannot figure out how to resolve it.

+5
5

, first - first ! - , . , , , , , calc-max , , , letfn. , my-max :

(defn my-max [ff & more]
  (letfn [(calc-max [m x] 
            (cond (empty? x) m
                  (> (first x) m) (calc-max (first x) 
                                            (rest x))
                  :else (calc-max m (rest x))))]
    (calc-max ff more)))

, , :

(defn my-max [& more] (reduce max more))
+8

, . , max.

(fn [& args] (reduce (fn [x y] (if (> x y) x y) ) args ) )
+14

, first fn , . ,

user=> (my-max 12 3 4 5 612 3)

, 12.

(defn my-max1 [fst & more]
  ((fn calc-max [m x]
     (cond (empty? x) m
           (> (first x) m) (calc-max (first x) (rest x))
           :else (calc-max m (rest x))))
    fst more))

fn

(defn my-max [x & xs]
  (cond (empty? xs) x
        (> (first xs) x) (recur (first xs) (rest xs))
        :else (recur x (rest xs))))
+4

, : , Clojure -

java.lang.Integer cannot be cast to clojure.lang.IFn

, , , , , - . ,

(smbl 1 2 3)

smbl , Clojure 1 2 3. smbl , , . , , 4e6, (first x) , first.

+1

Not as good as decreasing, but good ba:

(fn [& args] (loop [l args, maxno (first arguments)] (if (empty? l) maxno (if (> maxno (first l)) (recur (rest l) maxno) (recur (rest l) (first l)))))))

I can use cond

0
source

All Articles