My vim installation

In earlier days, if you wanted to install some plugins, you had to download a file and place it typically in your ~/.vim/plugins directory. Today there is a kind of package manager, called Pathogen.vim. This tool or plugin makes it easy to install plugins in a private directory.

Installing is very easy. Just run the commands:

1
2
mkdir -p ~/.vim/autoload ~/.vim/bundle
curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim

Now all other packages you will install are located in the ~/.vim/bundle directory. Before this works, you first have to add a line in the .vimrc file:

1
execute pathogen#infect()

I installed an extension ctrlp.vim by just going to the bundle directory and cloning the crtlp.vim repository from github.

1
2
cd ~/.vim/bundle
git clone https://github.com/kien/ctrlp.vim.git

Update also the runtimepath in the vimrc file:

1
set runtimepath^=~/.vim/bundle/ctrlp.vim

And run with a vim open the following command:

1
:helptags ~/.vim/bundle/ctrlp.vim/doc

Then the next time your vim is restarted, :help ctrlp.txt shows the help page. This extension is handy for browsing in a project directory. Just open it with ctrl-p

I also installed the following packages:

1
2
git clone https://github.com/mattreduce/vim-mix.git
git clone https://github.com/elixir-lang/vim-elixir.git

The vim-mix project has some commands for running mix commands, like :Mtest or :Mcompile. This can be used to run every time an elixir file is saved. Add the following code in the vimrc file.

1
2
autocmd BufWritePost *.exs Mtest
autocmd BufWritePost *.ex Mtest

Now everytime an exs or ex file is saved, the unittests are running in the project directory.

At last my complete vimrc file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
color koehler
set number
map <F1> :call BufferList()<CR>
map <F2> :Explore<CR>
map <F8> :vsplit<CR>
map <F9> :split<CR>
map <F10> :close<CR>
map <Down> <C-w>j
map <Up> <C-w>k
map <Right> <C-W>l
map <Left> <C-W>h
set expandtab
set tabstop=4
set shiftwidth=4
execute pathogen#infect()
syntax on
filetype plugin indent on
set runtimepath^=~/.vim/bundle/ctrlp.vim
autocmd BufWritePost *.exs Mtest
autocmd BufWritePost *.ex Mtest

Basic Types in Elixir

Elixir has like all programming languages some types.

Integers

There are for example integers. Decimal numbers may contain underscores. It is often used to seperate 3 digits from each other to have better readability. All of the following contains valid examples of integers

1
2
3
123
100_000_000
10_0_0

Atoms

An Atom is a literal, a contant with a name. If you know erlang, it is the same concept, but a different layout though. They must have a leading colon (:). In erlang they must begin with a small letter. But in elixir it does not matter because the colon does identifies an atom. Atoms are used a lot in elixir. Examples:

1
2
3
4
:ok
:test
:true
:True

Tuples

A tuple is an ordered collection of values. Once created, a tuple can not be changed anymore. They are written between braces {} and the different elements seperated by a comma.

1
2
{1,2}
{:ok, 1, "next"}

Lists

The syntax of a list is like arrays in other languages, written between [].

1
2
3
[1, 2, 3]
[:ok, 2, 3]
[]

You may think that this is an array, but in fact it is not. This really is a linked data structure. A list is empty or contains a head and a tail. Lists can be easily traversed linearly, but expensive to access in a random order. Like other data structures, a list is immutable. Once created, it can be never changed.

Keyword Lists

In many cases there is a need for a lists containing a key-value pair. Elixir has a shortcut for this syntax.

1
[name: "P1", street: "S1"]

Elixir converts this to the following:

1
[ {:name, "P1"}, {:street, "S1"}]

This means that the following evaluates without an exception.

1
[name: "P1", street: "S1"] = [ {:name, "P1"}, {:street, "S1"}]

In some cases, the outer brackets can be left out. If it is the last argument in a function call.

1
Mymodule.save arg1, [name: "P1", street: "S1"]

This can be written like this:

1
Mymodule.save arg1, name: "P1", street: "S1"

This syntax is more cleanly to write. But if you do not know this, it can be strange if you look at the source code of the save function.

first steps in elixir

Elixir, the language of the future? For me it looks a promising language. I do like the programming language erlang and python, but I assume that elixir can be handy for testing purposes too. The concepts look like erlang according to me. Lets have a first overview of assignments.

Suppose there is a variable and a number must be assigned to it. In any programming language that I know it is something like

1
2
iex(1)> var_a = 5
5

It seems that is is the same as in python or c, or whatever. But in fact this assignment is like in erlang. It is an evaluation, or just a pattern match. Ask always, what has to be done to evaluate this to be valid mathematically. Right, set the value of var_a to 5. For this the evaluation can be done in the other order, only if var_a has already a value. In case var_a did not have a value, a runtime error is raised.

1
2
3
4
5
6
7
8
iex(1)> var_a = 5
5
iex(2)> var_a
5
iex(3)> 5 = var_a
5
iex(4)> 5 = var_b
** (RuntimeError) undefined function: var_v/0

If another value is evaluated, for example 3, then a ValueError is raised.

1
2
iex(4)> 3 = value_a
** (MatchError) no match of right hand side value: 5

Lists can be bound to a variable:

1
2
3
4
5
6
7
8
9
10
11
12
iex(6)> lst = [1, 2, 3]
[1, 2, 3]
iex(7)> lst = [a, b, c]
** (RuntimeError) undefined function: b/0
iex(7)> [a, b, c] = lst
[1, 2, 3]
iex(8)> a
1
iex(9)> b
2
iex(10)> c
3

Command number 6 stores a list in a variable lst. Now, place it to another list. This can only be done with variables if the variable is on the left side, otherwise the code seems to think that the variables are functions. A kind of pattern matching occurs. lst is a list containing 3 elements. This can be matched by the list with the three variables a, b and c. So the variables are filled in with the correct values.

In case the list is more complex, this pattern matching is the same:

1
2
3
4
5
6
7
8
9
10
iex(11)> lst = [1,[2,3],[3,[4,5]]]
[1, [2, 3], [3, [4, 5]]]
iex(12)> [a,b,c] = lst
[1, [2, 3], [3, [4, 5]]]
iex(13)> a
1
iex(14)> b
[2, 3]
iex(15)> c
[3, [4, 5]]

But it is also possible to fill in some values to at the left side.

1
2
3
4
5
6
7
8
iex(17)> lst=[1,3,2]
[1, 3, 2]
iex(18)> [a,3,b] = lst
[1, 3, 2]
iex(19)> a
1
iex(20)> b
2

This is not too difficult to understand, no? There is also a kind of everything matches operator, or a don’t care. It is just an underscore, like in erlang or in python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
iex(24)> [1,_,b] = lst
[1, 3, 2]
iex(25)> b
2
iex(26)> [_,_,b] = lst
[1, 3, 2]
iex(27)> [_,_,b] = [1,2,3]
[1, 2, 3]
iex(28)> [_,_,b] = [2,2,3]
[2, 2, 3]
iex(29)> [_,_,b] = [2,2,3]
iex(30)> lst = [1,[2,3],[3,[4,5]]]
[1, [2, 3], [3, [4, 5]]]
iex(31)> [a,b,_] = lst
[1, [2, 3], [3, [4, 5]]]
iex(32)> a
1
iex(33)> b
[2, 3]

Here some more complex pattern matches are shown. The command 31 for example shows that it does not matter what is in the last element of the list. It can be a single value, or a list or a list in a list and so on.

There are other concepts in this language that we can handle. A variable can be evaluated or matched only once in one statement. For example

1
2
3
4
iex(38)> [a,a] = [1,1]
[1, 1]
iex(39)> a
1

A last issue that I want to handle is the pin operator. In erlang for example a variable can be set to a value only one time. In elixir it is possible to have that behaviour too, if an ^ is preceeded by a variable name.

1
2
3
4
5
6
iex(40)> a = 4
4
iex(41)> ^a = 4
4
iex(42)> ^a = 5
** (MatchError) no match of right hand side value: 5

Value 4 is placed into variable a. If ^a is used, then it can be evaluated if the right side is the same as what was already in the variable a. The variable can not be set a to 5 if a is preceeded by a ^. Some other examples are shown in the next code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
iex(45)> lst = [1,2,3]
[1, 2, 3]
iex(46)> a=1
1
iex(47)> [^a,b,3] = lst
[1, 2, 3]
iex(48)> a
1
iex(49)> b
2
iex(50)> [^a,b,3] = [2,3,1]
** (MatchError) no match of right hand side value: [2, 3, 1]

This operator operates inside of lists too. To conclude: the sign = is not an assignment, but an evaluation and the language tries to evaluate to True. This can be done by assigning some values to variables.

In a next post, I am going to cover other aspects of the elixir language.

Iterators

We all know that the for loop in python is very handy. We can loop a number of times and do something each time the code is running in the loop.
I did try it and came with the following solution:

1
2
for number in range(30):
print(number)

This is a very common code snippet. We also can loop over lists and even over dicts:

1
2
3
4
5
6
7
a = [1,2,4,5]
for item in a:
print(item)
b = { "one":1, "two":2, "three":3}
for key in b:
print("key {} has value {}".format(key, b[key])

But, should it not be very handy to loop over some class? Let’s for example create a kind of xrange, but a one that steps by value 2 and not by 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class myRange(object):
def __init__(self, max):
self.number = 0
self.max = max
def __iter__(self):
return self
def __next__(self):
if self.max > self.number:
num = self.number
self.number += 2
return num
else:
raise StopIteration()
for r in myRange(10):
print("number {}".format(r))

This will print the numbers 0,2,4,6,8

As you see, the iterator must have the functions iter and next implemented. The iter function will return the iterator itself, and the next will return the next value, when it is called by the for loop. In case the iterator ends, a StopIteration exception is raised. This exception is silently ignored by the for loop and this exception means that the for loop must end.

Most Wanted Letter

Again some nice puzzles that I solved and where the solution was much simpler than I expected. The standard libraries of python are very powerfull. We look at a first puzzle:

The description of the problem is as follows:

You are given a text, which contains different english
letters and punctuation symbols. You should find the most
frequent letter in the text. The letter returned must
be in lower case. While checking for the most wanted letter,
casing does not matter, so for the purpose of your search,
“A” == “a”. Make sure you do not count punctuation symbols,
digits and whitespaces, only letters.

If you have two or more letters with the same frequency,
then return the letter which comes first in the latin alphabet.
For example — “one” contains “o”, “n”, “e” only once
for each, thus we choose “e”.

I did try it and came with the following solution:

1
2
3
4
5
6
7
8
9
10
11
def keyf(a):
return a[1]
def checkio(text):
a = [x.lower() for x in text if x.isalpha()]
a.sort()
c=[(l,a.count(l)) for l in a]
result = max(c,key=keyf)
#replace this for solution
return result[0]

But there was a better and smaller solution. Just take all the letters of the alfabeth in lowercase
and take the same max key, but take the count of each letter in the original text and that it is.

1
2
3
4
5
import string
def checkio(text):
text = text.lower()
return max(string.ascii_lowercase, key=text.count)

This are fewer lines of code and make use of the string library.

Keeping non unique items in a list

I tried a new game at (http://checkio.org)[http://checkio.org]. This is a kind of game for programmers. Learn you programming skills by playing a game. Cool, not? The game contains some kind of problems you need to solve. An interactive programming environment is at your service in this game.
The first problem however was not so simple. I never needed that problem at this point, but it revealed some new things for me.

The problem is simple: I have an array of items. Just delete all items that are not unique in the list and return the other values as a list, with all duplicates in it and in the same order. For example:

1
2
3
[1, 2, 3, 2, 1] must return [1,2,2,1]
[1, 3, 1, 3, 2, 3] must return [1, 3, 1, 3, 3]
[5, 5, 5, 5, 5, 5] must return [5, 5, 5, 5, 5, 5]

Read More

globals in python

Today I am going to have some coding fun as I will call it. The following code was written by me. For the simplicity I just create messages with two characters. A message id character and an optional character

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Message(object):
def __init__(self):
self.__data = ""
self.__valid = False
@property
def data(self):
return self.message_id + self.__data
@data.setter
def data(self, input):
if input[0] == self.message_id:
self.__data = input[1:]
self.__valid = True
else:
self.__valid = False
@property
def valid(self):
return self.__valid
class MsgRead(Message):
def __init__(self):
super(MsgRead, self).__init__()
self.message_id = '1'
class MsgWrite(Message):
def __init__(self):
super(MsgWrite, self).__init__()
self.message_id = '2'
class GenerateMessage(object):
@staticmethod
def create_write(data):
msg = MsgWrite()
msg.data = data
return msg
@staticmethod
def create_read(data):
msg = MsgRead()
msg.data = data
return msg
@staticmethod
def gen_message(data):
msg = GenerateMessage.create_read(data)
if msg.valid:
return msg
msg = GenerateMessage.create_write(data)
if msg.valid:
return msg
@staticmethod
def generate(data):
msg = GenerateMessage.gen_message(data)
return msg
g = GenerateMessage()
a = g.generate("1a")
print type(a)
b = g.generate("2b")
print type(b)

Read More