Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure String Return Values

Tags:

clojure

lisp

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?

like image 782
echox Avatar asked Mar 26 '11 20:03

echox


1 Answers

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"
like image 168
geekosaur Avatar answered Sep 28 '22 02:09

geekosaur