How to return a Clojure Persistent List in Java


#1

Hi,

Using a simple source with one function as an example,

; simple-example.clj
(ns user)

(defn sample-list []
( '( 1, 2, 3 ) ) )

(defn whatthe []
( str “what the, world…?” ) )

, how do you return the list from sample-list() in Java, without getting the

java.lang.ClassCastException: clojure.lang.PersistentList cannot be cast to clojure.lang.IFn

error?

I’m using the loadResourceScript method, and getting the var. But when trying to invoke the method, and return the list as an object, that error appears.

I don’t think I’m doing anything syntactically wrong, because it successfully returns the string from whatthe.


#2

Hi @ClojureExplorer,

Alright, let’s break this down one step at a time. First, what’s going on in the function that’s working?

(defn whatthe []
  (str "what the, world... ?"))

(whatthe) ;; => "what the, world... ?"

Clojure’s evaluation semantics work like this:

  1. Parens mean function call.
  2. The “function position” item gets evaluated first. It’s the symbol str. Symbols get looked up in the namespace. In this case, it refers to the function clojure.core/str.
  3. Arguments get evaluated next. The argument here is the literal string “what the, world… ?”. Strings evaluate to themselves.
  4. The function is called on the arguments. The function is clojure.core/str, which converts its arguments to strings and concatenates them. So here, you’re converting your string . . . to a string.
  5. The value of the last expression in a function is returned. So you’re returning the string returned by str.

So just a note, you don’t need to convert the string. So we can rewrite it like this:

(defn whatthe []
  "what the, world... ?")

Now, for the one that doesn’t work.

(defn sample-list []
  ('( 1, 2, 3 )))
  1. Paren means function call.
  2. The “function position” item get evaluated first. It’s a list of three elements.
  3. There are no arguments.
  4. The list of three elements gets called like a function, but it’s not a function, so it’s an error.

In short, you’ve got an extra set of parens. What you want is:

(defn sample-list []
  '( 1, 2, 3 ))

I hope that helps!
Eric


#3

Roger on that, thanks Eric.

Also, this works

(defn sample-list []
( seq '( 1, 2, 3 ) ) )