Contrinue string chapter

rhgraysonii authored
revision 8cb298ea0e49d5c87b9883778f28a8a4d707f50e
On_Strings
# Strings

Strings are one of the most intrinsic things that we use to communicate. This book is essentially being parsed in your mind as a series of strings. Strings are often objects of input/output in programs to be modified, displayed, and fudged with. If you're familiar with a variety of languages you probably are of the understanding that depending on what you are working with, a string can be both an object or a primitive. In Clojure, we aren't functioning in an Object Oriented language. It is primarily functional in its application.

Though Clojure itself is not an object oriented language, it is, however, implemented in Java. The compilation results in the code being run as Java VM code. This results in a string in Clojure being compiled as an instance of a String object in Java, which is a series of char primitives.

Most of Clojure's data types are immutable, as mentioned prior. They never change. Clojure favors comparison of equality much moreso than comparison of identity. In most languages this is discouraged because the values are deeply built into the structure of each instance of an object. Thusly, Clojure compares content. An example:

(= "pants" ( str "pan" "ts"))

;=>true

However, in Ruby:

Now that we have defined a class, lets make some instances of it

a = String.new("hello")
b = String.new("hello")
a == b
>false
a.hello == b.hello
>true


Clojure makes this comparison cheap on resources. A Clojure object in this situation is keeping around a hash of itself, and this hash is what is compared rather than deeply inspecting it. This, however, only works if all parties involved are completely immutable. As stated, not ALL pieces of Clojure are immutable.

As with many other languages, strings in Clojure have many built in methods. Here are some examples:

(str)
;=>""

The str method will simply return an empty string if there are no other list items.

(string? "x")
;=>true

This operator will determine if a given item is a string. However, it cannot handle multiple arguments.

(string? "x" 1)
;=>clojure.lang.ArityException: Wrong number of args (2) passed to: core$string-QMARK-

There is also capitalize and chomp methods just like Ruby. They perform as expected (capitalize the first letter of a word, and remove a trailing newline, respectively).