Hamza Yerlikaya
Hamza Yerlikaya

Reputation: 49329

Clojure representing byte array

In java i would read the whole file in to byte array and do some processing with it. Now i want to implement the same algorithm in clojure.

What i am wondering is can i use a list instead of an array?

I know i can create array from clojure but what is the lisp way of handling this?

Upvotes: 11

Views: 1952

Answers (2)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91534

here is a lazy sequence of the bytes in the file and closes the file handle when the last byte has been read. If you work with sequences fed by huge files be careful not to hold onto the head of the sequence anywhere or you will run out of memory. It's ok to hold onto the file handle though in case you need to manually close it in an error condition.

(defn byte-seq [rdr]
  (let [result (. rdr read)]
    (if (= result -1)
      (do (. rdr close) nil)
      (lazy-seq (cons result (byte-seq rdr))))))

Upvotes: 3

pmf
pmf

Reputation: 7749

If the file in question is very large, you should always consider using a memory mapped file. clojure.contrib.mmap offers some functions to deal with that.

I know i can create array from clojure but what is the lisp way of handling this?

I don't know about the Lisp way, but the Clojure way allows you to use the sequence functions on arrays, so you don't have to decide between efficient representation and comfortable handling (which in my opinion is one of the points that makes Clojure so pragmatic).

Upvotes: 11

Related Questions