7

just a quick question while looking at Clojure....

Given the following REPL Session:

Clojure 1.2.0
user=> "bar"
"bar"
user=> (print "bar")
barnil
user=> (defn foo [] ("bar"))
#'user/foo
user=> (foo)
java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)
user=> (print foo)
#<user$foo user$foo@65dcc2a3>nil
user=> (print (foo))
java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn(NO_SOURCE_FILE:0)

Why isn't the String "bar" shown by the print function? It seems like the reader tries to resolve the return value of foo (which seems to be a String) as a function? How should be foo defined that print will write the string to the commandline?

2 Answers 2

16

I'm still a bit weak on Clojure as compared to various other Lisp-likes, but that's not right, is it? Should be

(defn foo [] "bar")

otherwise you've defined a function that tries to call the string "bar" as a function, which is consistent with your error.

mress:10004 Z$ clj
Clojure 1.2.0
user=> (defn foo [] "bar")
#'user/foo
user=> (foo)
"bar"
Sign up to request clarification or add additional context in comments.

1 Comment

I had issues with defining a cwd method at the root of my project. Calling (str cwd "src/foo.txt") mistook cwd as a first-class function object, returning "project.core$cwd@63764dsrc/foo.txt". Changing it to (str (cwd) "src/foo.txt") works as expected. I understand now that in an imperative language (Python), this is the difference between the statement len, and the operation len().
6

because Clojure tries to "resolve" first element of the any list as the function name when you in the last statment called print function it is called with one argument list (foo) whish is interpreted as call to the function foo. so far so good.

but function foo returns list ("bar") which is not ok..it is interpreted like call to the "bar" function which is not allowed..

if foo is like (defn foo [] "bar") than it will work because print will not receive ("bar") but just "bar" and do the printing

1 Comment

mmh, 2 correct answers 18 mins ago :-) I think the other is a bit more describtive, but still +1 :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.