Clojure Journey VII – Collection and Sequences

After talking about basic datatypes on our last post of this series, we can talk about array, list, map and sets. Clojure has a rich set of built-in data structures, and the key is know the difference between each one and when use it in to take advantage.

Vector

Let’s start talking about vector or “Array” from those coming from languages that use this term, probably the most popular and easy to learn structure that we’ll talk about here. Th

Vectors in Clojure behaves just like you expect from other languages (sometimes named Arrays), it’s a sequential allocation of memory allocation, where index starts from 0.

=> (vector 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
=> (type (vector 1 2 3 4 5)
clojure.lang.PersistentVector

Note that just like other languages, vectors are represented with brackets []. You can create a new vector, just using its literal, like this:

=> [1 2 3 4 5]
[1 2 3 4 5]

The result is the same as using the vector function, so, feel free to use the best way in the context. Vectors can be of nested types too, so don’t feel locked to only one type:

=> [1 2 "Don't Panic" :hi]
[1 2 "Don't Panic" :hi]

It’s interesting to note that you don’t need to separate the values by commas, in Clojure, spaces are seen like commas in other languages.

Now we have our vectors but we need to do things with it, to do our tasks Clojure provides a nice set of functions to interact with it, the simpler one is count, as the name suggests it returns the number of items in the vector.

=> (count [100 142 42 "Don't Panic"])
4

We can create a new vector with things at the end, using conj function :

=> (conj [100 142 42 "Don't Panic"] "Hello World" "Ola")
[100 142 42 "Don't Panic" "Hello World" "Ola"]

Note that you can pass N values as arguments and it will be returned in the new vector.

The same way that we use conj to add to the end of our vector, we can use cons to return a new sequence with arguments at the beginning.

=> (cons "Hello World" [100 142 42 "Don't Panic"])
("Hello World" 100 142 42 "Don't Panic")

But different from its cousin, cons only accept one argument.



A brief of Immutability

Did you notice that I used the term “new vector” while referring to the return value of the function? The reason that I used this term is because Clojure always will return a new vector, and not the same vector with one more item as some people (depending of the language that you come from) may expect.

The proof is simple, let’s bind a vector to an identifier, use conj to add something, and print the vector again:

=> (def our-vector [1 2 3])
#'user/our-vector
=> our-vector
[1 2 3]
=> (conj our-vector 42)
[1 2 3 42]
=> our-vector
[1 2 3]

Note how the our-vector doesn’t change, Clojure always returns a new vector and you can expect this behavior for almost anything while coding Clojure, immutability is one of the pillars of Clojure. In future post I’ll talk only about immutability and it advantages, but for now this is whats matters.

OMG! These structures are strong like a rock!

If we want to use the value you can bind it to a net identifier:

=> (def second-vector (conj our-vector 42))
#'user/second-vector
=> second-vector
[1 2 3 42]


Back to talk about functions that you can use with vectors, other nice function is the nth that returns the value the value in the given index (0-indexed):

=> our-vector
[1 2 3]
=> (nth our-vector 1)
2

Just to finish about vector, let’s talk about first/rest functions, just as you imagine, first will return the value at index 0 of your vector:

=> (def our-new-vector ["Don't Panic" 42 "Hello World" 23])
#'user/our-new-vector
=> (first our-new-vector)
"Don't Panic"

And as we already know about immutability, the original vector will not be modified:

=> our-new-vector
["Don't Panic" 42 "Hello World" 23]

And we have our rest function, that will return a new sequence will all values except the first of our vector:

=> (rest our-new-vector)
(42 "Hello World" 23)

And I don’t need to say again that the original vector will stay the same, right?

Using the first/rest functions we can access any value of our vector just using recursion, but if you just want to access the last value, you can use last of course.

=> (last our-new-vector)
23

I think that we know everything to get started working with vectors, now let’s talk a bit about lists.

List

I already talked a little about the list in my post about syntax, but basically, everything in Clojure is a list (If you don’t know about what I’m talking check the post and you’ll understand), if a list is what we use in almost everything in Clojure, let’s take a look on how we can use lists.

To create a list just put your data around parentheses , just like it:

(1 2 42)

But if you try to create a list in this way, it will raise an error like we talked in our previous post. Clojure will try to execute this list as code and will expect a function in the first value of the list, so, if we want to really use a list we need to tell Clojure to not execute this value, and we do this appending an apostrophe to the beginning of our list:

=> '(1 2 42)
( 1 2 42)

Another amazing thing about the list is that the count, first, rest, last, nth, cons works equal as you learned on vectors (and we’ll learn why soon), so, don’t need to learn again! But different from vector, if you use conj it will append to begging of the list.

=> (conj '(1 2 3 4) 5)
(5 1 2 3 4)

Just like vectors if you don’t want to create with the literal, you can use a function to do this job for you.

=> (list 1 2 42)
(1 2 42)

Have you noticed that you use a list to create another list?

[IMAGEM FUNNY]

Maps

It’s impossible to imagine programming nowadays without maps, or as some languages call “Hashes”, its the simplest, fastest and elegant way to represent real world structured data, in functional programming it gains more attention, because is probably the best way to do that.

To create a new map in Clojure, just as the other structures we have two ways, the function, and the syntax sugar, let’s start with the sugar way:

=> {:name "Otavio" :country "Brazil"}
{:name "Otavio" :country "Brazil"}

Just put your data inside a curly brackets and have a fun, but pay attention that it need to follow the “key and value” order and if you don’t put a even number it will crash.

To create the same map, you can use the function hash-map:

=> (hash-map :name "Otavio" :country "Brazil")
{:name "Otavio", :country "Brazil"}

One thing that you can do to make your maps declaration more readable is to put a comma between each pair.

=> {:name "Otavio", :country "Brazil"}
{:name "Otavio", :country "Brazil"}

Pay attention that we almost always use keyword as map keys in Clojure!

To access a value from a map we have few options, the most common way is to put the key that you want to access and the map.

=> (:country {:name "Otavio" :country "Brazil"})
"Brazil"
Let’s get things from the map with ourr new magic!

We can pass a default value, so if it don’t find the key it will return the default value that we passed:

=> (:language {:name "Otavio" :country "Brazil"} :english)
:english

Warning: To access data in this way the key need to be a keyword, otherwise it will raise an error.

Opposite from the previous way, we can pass the map and the key that we want too:

=> ({:name "Otavio" :country "Brazil"} :country)
"Brazil"

Of course we can pass a default value here too:

=> ({:name "Otavio" :country "Brazil"} :age 0)
0

How we are getting used, we have many ways to do things in Clojure, and I promise that this is the last way that I’ll teach how access data from map in this post:

=> (get {:name "Otavio" :country "Brazil"} :country)
"Brazil"

And we can pass a default value to get too:

=> (get {:name "Otavio" :country "Brazil"} :language :english)
:english

We have a few ways to access data from a map, and feel free to use the way that you think is better, but particularly I like the first way, passing the keyword and the map.

If we don’t want to pass default values and just know if the key exists in the map, we can use the contains? function:

=> (contains? {:name "otavio"} :name)
true

As you may imagine we can create nested maps two, just putting a new map on a key:

=> (def person {:name "Otavio" :age 199 :address {:country :UK :city :london}})
#'user/person

And to access data inside nested maps, is easy, just access the keys in the right order to get the data:

=> (:city (:address person))
:london

When dealing with maps we have the basic set of functions to deal with our data, the first the the assoc that we can use to add values to map, or edit.

=> (assoc {:name "Otavio" :country "Brazil"} :language :english)
{:name "Otavio", :country "Brazil", :language :english}
=> (assoc {:name "Otavio" :country "Brazil"} :language :portuguese)
{:name "Otavio", :country "Brazil", :language :portuguese}

And in a meaningful way, we can use dissoc to remove something from the map.

=> (dissoc {:name "Otavio" :country "Brazil"} :country)
{:name "Otavio"}

It’s important to remember now that almost everything in Clojure is immutable, and maps are immutable, every operation that we are doing on our maps are always returning a newer one.

We can obtain all values or all keys from a map, using the vals and keys function:

=> (vals person)
("Otavio" "Brazil")
=> (keys person)
(:name :country)

And we can merge maps into one just using the merge function, we can pass many maps as we want and remember that if two or more maps have the same key, it will use the value from the rightmost map passed to the function.

=> (def person {:name "Otavio" :country "Brazil"})
#'user/person
=> (merge person {:age 199 :language :english} {:name "Henrique"})
{:name "Henrique", :country "Brazil", :age 199, :language :english}

Now we know enough about maps, and we already learned a lot about vectors and lists, now it’s time to learn a little bit about how to do things with our collections.

Sequences, the magic behind collections

When dealing with our collection we have common functions that we can use (As we saw with cons or first in this post for example), one great example is the first function:

=> (first [1 2 3 4])
1
=> (first '(1 2 3 4))
1
=> (first {:name "Otavio" :country "Brazil"})
[:name "Otavio"]

If we stop to think about it, its a little bit curious, we’re not in a object-oriented language where each object has it own “fist” function, we’re calling the same first function to different structures and its returning correctly… Wouldn’t it be correct to have one function for each structure like first-vector or first-map, just like elisp has?(This example about elisp is a beautiful example pointed by Daniel Higginbotham at his book Clojure for the Brave and True)

Other nice option would be use an if statement to select how to take the first item of each collection, but it didn’t sound escalable if we have tons of collection in our language right?

Clojure has a more elegant way to solve this problem and it’s through abstractions, did you realized that sometimes in this posts I said that some function return a sequence? For example, if I call cons on on a vector, it will not return a new vector, it will return a sequence, take a look:

=> (cons 5 [1 2 3 4])
(5 1 2 3 4)

It can looks like a list, but its a sequence, I promise!

const like many other functions of Clojure will work if you pass any data structure that implements the sequence interface. To implement a sequence interface and be a seq the data structure need to respond to three function: first, rest and cons.

=> (cons 5 [1 2 3 4])
(5 1 2 3 4)
=> (first [1 2 3 4])
1
=> (rest [1 2 3 4])
[2 3 4]

If one data structure respond to these functions this structure are called seqable by Clojurists, when can call the seq function on it and it will return a sequence:

=> (seq [1 2 3 4])
(1 2 3 4)
“seq” a new magic!!!

seq transforms our structure in a new sequential structure that behaves like a list, a function like first only expect that you pass a structure that implements that interface, so it call seq on every structure that you pass, and perform the operation.

Sequence Functions

Sequences brings a great power to Clojure, and if a collection is seqable a rich set of functions can be used, and fortunately all data structures that we learned in this posts, are “seqables”, and we can use all these functions!

We already learned few of them, like first, rest, cons, last but the true magic stands on functions that can make processes in our collection, like, map, reduce, filter and many others (Depending of your previous experience you’re already used to some of them).

Map

map is an ambiguous term in Clojure, because it represent the data structure the we saw (commonly called hash in other languages) and it also represent a common function that can be used on sequences. When talking about the function, it’s used when you want to create a new sequence by applying a function for each element of our sequence.

Imagine that we have a vector with maps, and each map represent a person:

=> (def person [{:name "Otavio" :country :br}
     {:name "Gabriela" :country :uk}
     {:name "James" :country :us}])

And we want to create a new sequence only with the name of these person, we can use map:

=> (map :name person)
("Otavio" "Gabriela" "James")

In this example we passed the function :name to map apply it for each item of our sequence and return a new sequence with the results of each function (:name) call.

Let’s get the names from map

It’s important to note that functions that operates on sequences, returns a new sequence, so if we want a vector again, we can use the into function (other common seq function) to put the items of our sequence inside a empty vector:

=> (into [] (map :name person))
["Otavio" "Gabriela" "James"]

When we learn about functions we will use map it a lot, and you’ll see the true magic behind it.

For

Other common seq function is the for which is very similar to what we see in other languages, it loop through our collection binding the current value to some identifier, the same operation of our last example using for will looks like:

=> (for [p person]
     (:name p))
("Otavio" "Gabriela" "James")

In this example we tell Clojure to loop through our collection person and bind each value to a identifier p, and after that call :name on p.

But let’s try to avoid using for for everything, its much more elegant and functional minded to use functions like map, reduce to do the things, mostly we can use them to solve our problem.

Reduce

The last function that we’ll see in this post is reduce, we will pass a function and a sequence to it too, just like map, but different from map the response of each function will be given as argument to the next one and at the end of our sequence, it returns the result. It sounds a little confusing while reading but it’s simple, the easiest example is use a reduce to obtain the sum of all elements in a vector:

=> (reduce + [26 23 05 42 19 100 120 123])
458
Reduce working

We can give a staring value if we want too and second argument:

(reduce + 10 [26 23 05 42 19 100 120 123])
468

Know how to use reduce correctly can be very powerful and we’ll see this in a future post, but now its enought.

Much more

We’ve a lot of functions to interact with our sequences, but I don’t want to take a deep view in each of them, so, I pretty recommend to read this post and learn other functions if you want, or wait to learn while having a fun with Clojure.

Off: What’s the difference between vectors and lists?

After reading this post a lot of questions come to mind, but the most frequent one can be: “What’s the difference between vectors and lists? Both look the same for me!”, the two structs look the same at first view but behind the scenes both are different.

The difference is simple, and for most people (except me) will remember college days, vectors are equal vectors of other languages, it is a sequential chunk of memory allocated (Did u Remember how to use malloc?), and lists are implemented like a linked list behind scenes.

Lists and Vectors under under the magnifying glass

This difference between each implementation creates advantages and disadvantages for each one, for example, add a new value to a list is simple, the language only needs to create a new “node” and add it to the end or beginning of the list, but add a new value in a vector we need to relocate the chunk of memory and them add the new value.

Otherwise, if you want to access a value from your vector, it will be faster, it only needs to calculate some arithmetic and access, a linked list will need to transverse all the list calling the next node, and it will take a while. (if you want a good post with nice benchmarks with time, check this post)

Both structures look similar but are different on an x-ray, both have its disadvantages and advantages, so you need to know where to use each one.

Conclusions

This is not a short read but of course, we learned a lot, now we know how to use Clojure data structures, the dream of immutability, and the magic of sequences.

We are progressing on our journey of becoming Clojure Wizards.

Next steps

As a good complement to this reading, I pretty recommend to read sequence documentation and learn about other functions that interact with sequences.

On next post we’ll talk about functions, high order functions, parameters, and much more.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares at gmail.com), pm me on my Twitter or comment on this post!

Clojure Journey VI – Data

Data is the core of all computer application, an information system basically receives information as input, executes operations and produces some output. Data is the core of computation, we execute operations using data, and as programmers we need to have ways of represent data at computer-level.

With this requirement, engineers and computer language hackers, created a way of represent data at software level classifying them in different types, and this type will represent a range of possible data and the way that it will behave when dealing with hardware.

All programming languages has a set of datatypes to deal with basic data, and imagine a language without them is almost impossible, Clojure of course has set of datatypes.

This post can look kind of boring but it’s necessary to study it before we start learning about functions in the next posts. It’ll do my best to this post don’t look boring and be short.

Hosted Types?

As a hosted language on JVM, most of its datatypes are from Java, and as we know, its heavy-tested for more 20 years, with excellent performance and interoperability, as we will see, Clojure strings are java.lang.Strings and so on.

To check type of something in Clojure, just use the function type, let’s start exploring with numbers, Clojure has it’s integer numbers that we already used in our journey when dealing with arithmetical operations:

=> (type 1)
java.lang.Long

As we see, the type is mapped to a Java type (remember that Clojure is build on top of JVM), other common types behave like this:

=> (type "Hello String")
java.lang.String
=> (type true)
java.lang.Boolean
=> (type 42.42)
java.lang.Double
Clojure primitives are java types

As supposed, you can use string to represent text, boolean to represent true/false and double to represent fractional numbers.

Numbers

Most of languages includes a float type, but as you should know, floats is not good enough, so, doubles are default in Clojure.

=> (type (+ 41.0 1.0))
java.lang.Double

floats are not banned at all, and Clojure has it, but it’s not the default, if you want to use it, you need to make a type conversion:

=> (type (float (+ 41.0 1.0)))
java.lang.Float

Just to keep talking about math, Clojure has a type that is not common on most languages, it’s called ratio that is useful to represent fractions:

=> (type 1/3)
clojure.lang.Ratio

And as we already seen, we represent integer numbers with integer type:

=> (type 1)
java.lang.Long

We can do mathematical operations on number as expected, just remember to use the polish notation, as we see in the last post.

=> (- 52 10)
42

One of the most important things to note here, is that if one number is fractional, the result is fractional, but you can do operations with integers and doubles interacting.

=> (- 52.0 10)
42.0

Text

You can represent strings in Clojure just putting any text inside double quotes:

=> (type "I'm a text")
java.lang.String

With the function str you can convert almost everything in String, just try:

=> (type (str 1))
java.lang.String

Clojure has it character type too, just type \ before a single char:

=> (type \t)
java.lang.Character

Logical Values

Logical values are represent by pure true and false, no complexity here!

user=> (type true)
java.lang.Boolean
user=> (type false)
java.lang.Boolean

And do logical operations with it too:

=> (and false false)
false
=> (and true true)
true
=> (or false true)
true
=> (not true)
false

In Clojure we only have two false values false and nil that we will see next.

Keyword

Keyword is a difficult topic to explain, folks coming from Ruby or lisp already know what I’m talking about. They look like string, but aren’t string, but are dedicated to be used as identifiers, they are just themselves, and you common will see as a map key for example.

They start with : fallowed by a text:

=> (type :keyword)
clojure.lang.Keyword

On the next post we’ll see more about keyword when dealing with maps.

Symbols

Symbols usually refers to something else, like functions, values. During the eval process they are evaluated to the value that its referring. To better understand it, let’s do and example.

We define a variable called hello, with the String “Hello Otavio”:

=> (def hello "Hello Otavio")
#'user/hello

Now if we just print the hello, as expected it will the string binded.

=> (println hello)
"Hello Otavio"

And if we check the type of hello:

=> (type hello)
java.lang.String

It will return the type of what is binded to hello and not the type of it, this occurs because evaluator first eval hello and look for what is binded, before call type. To check the true type of hello we need to delay the evaluation as we saw in the last post:

=> (type 'hello)
clojure.lang.Symbol

And that is our symbol. We already used a lot of symbols in this post, other example is the functions that we used:

=> (type 'println)
clojure.lang.Symbol
=> (type '+)
clojure.lang.Symbol
=> (type '-)
clojure.lang.Symbol

As we will see in future, symbols can have a namespace separated from the name by forward slash.

Fun fact from Clojure doc: There are three special symbols that are read as different types – nil is the null value, and true and false are the boolean values.

Regex

Regex has its own datatype in Clojure too, to represent a regex just use a hash fallowed by a string:

=> (type #"regex")
java.util.regex.Pattern

And with no surprise we will have a java datatype Pattern represented.

I will not dive deep into how to use regexs, but in the standard library we have good functions already built to deal with them, check this post if you want to learn more.

And Finally…The emptiness, the void, the villain!

Pay attention on nil monster or it will destory you!!

We’re talking about nil, the value that represent nothing, the emptiness. For those who already code something, you probably know it, in some languages are called Null, nil or None, it can be called a billion dollar mistake (watch this excellent talk anyway).

The rule is simple, nil is type nil and to represent nil just type nil:

=> (type nil)
nil

Next steps

On the next post we will see the collections, and understand each one and its use cases, for now to don’t extend this post we’ll finish here.

As a nice exercise for this post, check Clojure cheatsheet and you’ll see nice functions to deal with these datatypes.

Conclusions

Clojure has simple datatypes, and a uncommon datatype called ratio, one of the interesting things its that Clojure uses Double by default, so we avoid to use Floats.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares at gmail.com), pm me on my Twitter or comment on this post!

Clojure Journey V – Simplicity, Evaluation and Syntax

Most of the time that I heard someone talking about Lisp family languages, probably was something like “that ugly language, why people program with that?”, “why so many parentheses?”, unfortunately since I started to learn Clojure, I hear it twice more.

This post is the fifth of a long journey on learning Clojure, and the first to really talk about code, but it can be served to learn about any language of the LISP family, this post will talk about syntax of the language, and the most important, we’ll understand why LISP languages look like this, the philosophy behind.

When you learn every language, most of the books in the first chapters is like a cake recipe, a long and boring list of all statements of the language, control flow, loops, var declarations, and much more.

Back to the day that you started to learn programming, probably you started with simple math and strings:

1 + 1;
=> 2
"Hello World";
=> "Hello World"

After that you learned about variables:

var age = 23;

Some control flow:

if (10 > 5) {
  "Hello World"  
}

And the most strange thing in every language, the for loop:

for (var i = 0; i < 10; i++) {
  console.log(42)
}

Probably you’re questing yourself about what I’m talking about, but have you looked at this common languages statements and noticed that they didn’t follow any logic or consistency in the syntax? The traditional for statements is not simple, we’re just used to view it all day. These syntax is not simple, and that’s the point.

Simplicity

In LISP family languages all the code follows the same logic, and after you’re capable of understand one expression, you’ll be able to understand the entire language. It doesn’t have many special forms, or something different from the rest, and that’s why “simplicity”is one of the worlds in this post title! Let’s take a look at some Clojure code, starting from the classical:

=> (println "Hello World")
Hello World

Let’s see some arithmetic:

=> (+ 1 2 3 4)
10
=> (= 1 2 3)
false
=> (+ (* 2 2) (* 3 3))
13

Can you imagine how if looks?

=> (if (> 2 1) "Greater" "Smaller")
"Greater"

What all these expressions have in common? They follow the same pattern. Let’s take a look:

LISP family syntax

In the image, the expression xxx is read as a list, the first element can be called “function position”, and the rest as arguments. When evaluating it will always try to evaluate the first item as a thing to invoke (you can think like a function, but sometimes can be other things like macros), and the rest as arguments the invoked.

Positioning the “function” before its arguments it’s called prefix/polish notation, the expression (f x y) looks a lot like the traditional mathematics notation f(x, y). All lisp expressions use polish notation.

Evaluation

During the process of evaluating expressions, it will evaluate each argument of the expression and then invoke the function of the first position with the result of evaluating each argument, in other words, it will evaluate all expressions from the innermost to the outermost recursively, forming a evaluation tree. Let’s assume (+ (* 2 2) (* 3 3)) as our example:

Evaluation Tree

For those who already studied programming languages design probably realized that this evaluation tree looks a lot like an AST (Abstract Syntax Tree), and it’s kind off.

You may have noticed that the numbers in the bottom of the evaluation tree are evaluating themselves, and it leads us to another important topic.

Different from other languages, Clojure doesn’t have statements, it has only expressions that evaluates to a value, and its programs is composed of n expressions. Every form not handled specially by any macro or special forms is considered a expression by the compiler and it will be compiled and has it’s value returned.

Most literal Clojure forms evaluate to themselves, except symbols and list, that’s why numbers was evaluated to themselves in the evaluation tree image. Other common examples of forms that evaluates to themselves are, booleans, strings, characters and keywords. Symbols are resolved based on a set of rules, but in general, it will look for what was “binded” to the symbol.

=> "String"
"String"
=> 42
42
=> :keyword
:keyword

It will try to evaluate everything, but we have a way to delay this process and say “don’t evaluate it, just return it raw”, just put an apostrophe before your expression:

=> '+
+
=> '(+ 1 2)
(+ 1 2)
=> 'variable
variable

Syntax

If you read the text so far, probably you already know how to write an expression and how literals are evaluated, you also know how to delay a evaluation using the apostrophe, now we can talk about one of the most interesting thing in LISP family languages, the “code as data and data as code” foundation.

Languages that are from LISP family, have a data structure called list, lists are basically zero or more forms enclosed in parentheses (1 2 3 42) is a example of one list with integers 1, 2, 3 and 42, and now comes the plot… Other examples of list is (+ 1 2 3) or (println "Hello World").

OMG! It’s a LIST

All the programs are composed of lists, and LISP/Clojure is defined in terms of evaluate its own data, and not a stream of keywords like other languages. LISP stands for LIST-Processing, and it explain this name.

Languages that have its programs represented by its own data are called “homoiconic”, and LISP family languages are one of them, based on this the affirmation “code is data and data is code” emerges and it is commonly used when talking about Lisp/Clojure.

When writing Clojure probably you’ll use lists as a data structure to store data, but if you try to use it to store a list of integers, probably you’ll get error during the evaluation proccess:

=> (1 2 3 4)
Execution error (ClassCastException) at user/eval2018 
(REPL:1)
java.lang.Long cannot be cast to clojure.lang.IFn

If we take a look at the error, java.lang.Long cannot be cast to clojure.lang.IFn, this error is saying that a integer can’t be cast as function and this error occurs because we tried to evaluate a list without any function in the first position, by default when evaluating any list, the Clojure reader tries to find a thing to invoke in the first position, that’s why when evaluating a list just as data structure, clojurists use the apostrophe to tell Clojure to not try to evaluate it:

=> '(1 2 3 4)
(1 2 3 4)
=> '(+ 1 2 3 4)
(+ 1 2 3 4)

And that’s the way that you usually will see programmers using lists as data inside Clojure programs, in a future post we’ll talk about how to use it.

Let’s finish our study about syntax with an experiment, Clojure has a function in it’s core named eval, if we pass a valid list, it will evaluate it:

(eval '(+ 1 2 3))
=> 6

This is the core of the REPL, and with Clojure simplicity, we can write our own in a simple way:

(loop [] (println (eval (read))) (recur))

Combining a function to read user input read, one to eval this input eval, print the result of evaluation with println and finally loop infinitely doing it. Run it and you’ll have your own read-eval-print-loop (REPL).

Invoking REPL

Conclusions

This a long post but essential on our journey, we ha been introduced to Clojure syntax and the logic behinds it. We learned about the famous “code is data and data is code” jargon, beautiful behind lists and built our own REPL.

LISP/Clojure syntax is beautiful and simple, it can afraid people because it’s different from what we’re used to, but if we study we start to understand it fast!

Now that we know the syntax, we can take a look in data types on the next post, and after that advance to functions. Some topics are missing in this post like special forms, but in a future post we’ll talk about it.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares at gmail.com), pm me on my Twitter or comment on this post!

Useful Links

Evaluation, Clojure docs

The Reader, Clojure docs

Syntax, Clojure docs

Homoiconicity, Wikpedia

Polish Notation, Wikpedia

S-expressions, the Syntax of Lisp

Lecture 1A: Overview and Introduction to Lisp

Why code-as-data?

Hitchhiker’s Guide to Clojure

Clojure Journey IV – Leiningen and the famous REPL

In the previous chapters we set up our development environment, now it’s time to to get our hands dirty.

First of all we need to have Java installed, Clojure is a hosted language, and it compiles to JVM bytecode, so, we need Java installed.

After it install Leiningen fallowing the install instructions, it is the most popular build/dependency management tool for Clojure, and we’ll use it a lot while learning Clojure.

After install, just call lein at your terminal, and it should prompt help instructions.

REPL

Its is one of the most important thing in your Clojure development flow (and should be in every language, if its available), it will give you a interactive programming experience.

REPL stands for “Read–eval–print loop” its basically a interactive interpreter for one programming language, it was originally invented by LISP (the Clojure grandfather), and sice it a lot of programming languages has adopted it own (Clojure, Ruby, Python, JavaScript and much more).

This can sound like a bullshit for everyone that’s already used to programming in one language that already have one, but from the folks coming from environments that doesn’t have it, will be beginning of a new era, an era with REPL!

Just open your terminal and type lein repl and it will start a new REPL for you:

If you don’t want to use lein to start our REPL, just type clj and it will start too.

$ > lein repl
nREPL server started on port 46213 on host 127.0.0.1 - 
nrepl://127.0.0.1:46213
REPL-y 0.4.4, nREPL 0.7.0
Clojure 1.10.1
OpenJDK 64-Bit Server VM 1.8.0_252-b09
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)
 Results: Stored in vars *1, *2, *3, an exception in *e

user=> 

Now every expression that you type will be evaluated:

user=> (+ 41 1)
42

In one future post, we’ll learn how to integrate it with our text editor and have a full interactive programming experience!

REPL is not only evaluate expressions, in the future we’ll learn how to use it for debuggind, run test and much more, but for now, we’ll use it only for evaluating expressions while learning the beginners things!

Leiningen

Visualizar(abrir em uma nova aba)

One of the most fantastic thing about leiningen is to create a new project, is just one command you have a full project skeleton:

$> lein new app hello-clojure
Generating a project called hello-clojure based on 
the 'app' template.

Now just open it inside your editor and start exploring our project! One of the things that you need to note is the file project.clj, it is used by leiningen and it have important information to it build your project, like dependencies and the main function (the first function to run in our project). I think that if you already program other languages you know what this file is. For now you just need to think a lot about this file, in the future we’ll go deep.

Just to test our project, open the file src/hello_clojure/core.clj and change the println expression to any message:

(defn -main
  "Hello Clojure, I love U!"
  [& args]
  (println "Hello, World! I'm lovin Clojure"))

Now just go to your terminal and run your project with lein run:

$ > lein run
Hello, World! I'm lovin Clojure

That’s wonderful, right? With lein we can run our tests too, just type lein test, and you will run all tests of your project (leiningen app template comes with one test that’s easy to fix, it’s your mission try it).

We created our first project hello-clojure, tested with lein run, it’s time to build it! To build is very simple, just type lein uberjar and wait it finish.

After it, you should have a jar file inside target/uberjar directory in your project, just navigate to ir, and run it as a jar:

$ > java -jar hello-clojure-0.1.0-SNAPSHOT-standalone.jar 
Hello, World! I'm lovin Clojure

Leiningen templates

Leiningen has a lot of templates to use with the command leiningen new, it has a template for almost everything, and you can check for templates here. If you already waste some time in the internet looking for examples of skeletons of projects in X languages, this is for you! if you need a skeleton for CLI, just look at it, if you need something to webapps, just look at it! Its useful a lot.

We used the app template because its the most basic template, and it represents a common structure for Clojure apps, it can be very useful on the next steps of our journey.

Conclusions

We learned a lot about Leiningen in this post, now we know how to create projects, run, test and build it… But we learned something more important, something that we’ll use a lot through our journey, we learned how to use REPL!

REPL is one of the most powerful tool that we’ll use, and it will help a lot while studying to quick evaluate expressions, get used to it, and you’ll be a great Clojure wizard.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares at gmail.com), pm me on my Twitter or comment on this post!

Follow my blog to get notified every new post:

Check my last posts:

Clojure Journey III – Emacs for Beginners Course

On my last post I talked about why I chose Spacemacs to be my text editor while coding Clojure, installed it and made a nice first setup. In this post I’ll talk about some workflows/commands that I think is important to have a great and smooth coding.

This post probably will be one of these posts that keep opened in your browser and you read it everytime that you need to remember something.

Neotree

First let’s talk about our tree explorer, on the last post I installed the neotree that is similar to NERDTree(from vim), and started to using it.

The first thing that I did was to bind the open/close of it to F8 key with the fallowing code:

(global-set-key [f8] 'neotree-toggle)

Now just press F8 and your neotree will open.

Opening neotree

To navigate inside Neotree just use your moving keys (arrow keys or HJKL), if you have any question about it, you can just type ? and a nice window will be displayed with everything that you may need:

Neotree help page

And this image saved me from writing at least 500 words, this image has everything that you will need related to Neotree.

If you don’t want to open neotree with F8 you can open by pressing SPC + f + t.

Window

Split windows is a common move to every programmer, to split is easy, just press ESC to go back to visual mode (if not already), and press: SPC + w + / to split vertically or SPC + w + - to split horizontally, where SPC is your space key. If you don’t want to use SPC, M-m + number will work too.

M-<letter> stand for alt + m

Spliting Emacs Window

To navigate between window is simple, just press SPC and the number of the window that you want to go, like SPC + 2 to go to window 2. But how to know the window number?

Spacemacs window numberr

If you’re using spacemacs, your window number will be displayed by default on the bottom left corner of your window, as the pink arrows of the image is pointing. The current window will always be in different color (as the example, window 2).

Opening/Searching Files

Open using neotree

If you want to open a file inside a window, the easiest way is to open using Neotree, just go to the window that you want to have a file opened, open your neotree, navigate to the file and open it.

Opening file by Neotree
Project search aka Ctrl + P

But if you don’t want to search for the file in your neotree, you want something more like the famous ctrl + p command from other text editors? In spacemacs with helm (the setup that I’m using), it’s very simple, just type: SPC + p + f and a window will open, just write the name that you’re searching for, and press ENTER to open in the current window.

Searching for a file using spacemacs and helm projectile

Buffers

Now we know how to manage our windows, is time to understand and manage buffers! Technically… Windows displays emacs buffers!

Everything that you open inside emacs resides on what is called “buffer”, every code, really everything! And the plot is, if you close your file/window with the traditional :q! (if you use vim mode), this code isn’t close at all, the buffer still alive!

Too see your buffers just type C-c + b and a window will open with a list of all buffers.

C-c stands for ctrl + c.

List buffers

But this window is not very useful…If we want to open a buffer the best way is to use the buffer search (similar to the file search that we see previously), just press C-x + b and you’ll have a full interactive search for buffers:

Helm buffers find

Just search for the wanted buffer and press enter to open it. If you use C-c + o it will open in a splitted window. (If you just want to open in the current window, just type enter)

Search on spacemacs bufferr

A nice shortcut is to press SPC + tab to change to the last buffer!

All the buffers keep alive, ok! But how do we kill them? Just press C-x + k select the buffer and press enter!

Search on project

To search for a pattern across all the project is very easy, just type: SPC + / and start writing your pattern:

Global search spacemacs

If you press C-c + o like in other commands, it will open in a splitted window.

Replace

It has a nice built-in way to do search/replace inside project too, it ‘s simple, SPC + p + R (pay attention on capitalized R) . After this it will ask for a pattern to replace, and what to replace, after this it will open a window with the first match, press y if you want to replace and n if no. Do this for all matches.

Search and replace

Search for commands

Emacs comes with a global commands search, just type M-x` and write what you’re searching for.

OFF: Themes

If you want to install more themes is very easy! You can install a layer names themes-megapack (If you don’t know how to install layers read my last post) and you’ll have more than 100 themes to choose.

OFF: Games inside editor

Emacs comes with some games installed, just open the global search with M-x and write the name of one of the games, like, tetris!

Tetris on emacs

Remember: With great power comes great responsibility.

Conclusions

This is a short and beginner-friendly emacs tutorial with all flows that I think is important to get started in a new text editor.

I hope I haven’t forgotten anything important to get started with it.

On the next posts related to Clojure, I’ll be using my spacemacs as my text editor, I’m loving to use it and I want that everyone that trries to start using it, have a great experience too.

Final thought

If you have any questions that I can help you with, please ask! Send an email (otaviopvaladares at gmail.com), pm me on my Twitter or comment on this post!

Follow my blog to get notified every new post:

Check my last posts: