Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a LazySeq of Characters to a String in Clojure?

Let's say I have a LazySeq of java.lang.Character like

(\b \ \! \/ \b \ \% \1 \9 \/ \. \i \% \$ \i \space \^@) 

How can I convert this to a String? I've tried the obvious

(String. my-char-seq) 

but it throws

java.lang.IllegalArgumentException: No matching ctor found for class java.lang.String (NO_SOURCE_FILE:0) [Thrown class clojure.lang.Compiler$CompilerException] 

I think because the String constructor expects a primitive char[] instead of a LazySeq. So then I tried something like

(String. (into-array my-char-seq)) 

but it throws the same exception. The problem now is that into-array is returning a java.lang.Character[] instead of a primitive char[]. This is frustrating, because I actually generate my character sequence like this

(map #(char (Integer. %)) seq-of-ascii-ints) 

Basically I have a seq of ints representing ASCII characters; 65 = A, etc. You can see I explicitly use the primitive type coercion function (char x).

What this means is that my map function is returning a primitive char but the Clojure map function overall is returning the java.lang.Character object.

like image 690
Robert Campbell Avatar asked Nov 06 '09 14:11

Robert Campbell


People also ask

How do I assign a char to a string?

We can convert a char to a string object in java by using the Character. toString() method.

How do you define a string in Clojure?

In Clojure, strings are text between a pair of " (double quote) characters. The ' (single quote) isn't used to express strings in Clojure. When we want to use double quotes within a string, they must be escaped by \ (backslash).


1 Answers

This works:

(apply str my-char-seq) 

Basically, str calls toString() on each of its args and then concatenates them. Here we are using apply to pass the characters in the sequence as args to str.

like image 127
Siddhartha Reddy Avatar answered Sep 17 '22 21:09

Siddhartha Reddy