0

this is my first question here and i hope you can help me. I am programming a merge function in clojure. I test my code on tryclojure and got the error in the title.

Here is my Code

(def merge
(fn [lon1 lon2]
{:pre[(every? number? lon1)(every? number? lon2)]
:post[(every? number? %)]}
(cond
(empty? lon1) lon2
(empty? lon2)lon1
:else
(cons (min (first lon1) (first lon2))
(merge (rest lon1) (rest lon2))))))
#'sandbox7750/merge
> (merge (1,2,5) (3,4))
java.lang.ClassCastException: java.lang.Long cannot be cast to clojure.lang.IFn

So, whats the Problem here? Looking forwards to an answer :)

greetings

1
  • Could you please enhance your question? (code indents, upper/lower case letters in sentences) Commented Jun 6, 2016 at 9:53

2 Answers 2

0

First of all you need to quote lists otherwise they are evaluated and their first element is treated as a function to be called and thus the exception:

(1,2,5)
;; => java.lang.ClassCastException: java.lang.Long cannot be cast to clojure.lang.IFn

Quoting will help you to get a list with numbers:

'(1,2,5)
;; => (1 2 5)

It's also more idiomatic to not use element separator (like ,) and you can see the form printed above ((1 2 5)).

As it seems it's an exercise, I will let you fix other issues in your merge function.

4
  • Thanks for your Input, it was an excercise indeed. I also had some minor mistakes in my else part. Here is the new and working code: code (def merge (fn [lon1 lon2] {:pre[(every? number? lon1)(every? number? lon2)] :post[(every? number? %)]} (cond (empty? lon1) lon2 (< (first lon1) (first lon2)) (cons (first lon1) (merge (rest lon1) lon2)) :else (cons (first lon2) (merge lon1 (rest lon2)))))) Commented Jun 9, 2016 at 7:26
  • isnt there something like auto formatting? this code sucks to read.. Commented Jun 9, 2016 at 7:28
  • You can just copy formatted code from your editor, paste it into StackOverflow editor, select the code snippet and click the {} icon to mark it as code snippet. Commented Jun 9, 2016 at 7:31
  • well this wont work in the add comment section :) as you can see my first post was formated. Thanks for your help, i am good now Commented Jun 9, 2016 at 7:51
0

The right call is (merge '(1 2 3) '(4 5)) or (merge [1 2 3] [4 5]) (commas is optional). When you write unquoted list (1,2,3) a first element considered as the function. 1 is not a function and you get the error message.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.