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

First usage of elixir


I bought a little book of a new programming language named Elixir. The book is called Programming Elixir. I read the first two or three chapters and I must say that it is indeed different from other languages I know. It has some elements of Erlang, but not all.

Then I tried to install elixir on my mac. I followed the guidelines on the official webpage:

1
2
brew update
brew install elixir

This went fine. I could start the interactive shell with the command iex, like it was in the book.

1
2
3
4
Erlang/OTP 17 [erts-6.1] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Interactive Elixir (0.14.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>

I could do for example 3 + 4 and I saw :

1
2
3
iex(1)> 3 + 4
7
iex(2)>

I tried other examples and then I decided to close the shell. I did not read about a command to close the shell, so because I saw Erlang on the shell, I tried the command q. In Erlang it is q(). Therefore I also tried it as a function, but no luck.

Aparently there is no command implemented yet to close the interactive shell correctly. What we should do is the following like it is possible in Erlang too:

1
2
CTRL-G 
press now q

My first try with elixir was already ended with a call to google. Nice I would say. Let the explorer in me begin to explore the language.

Variable keywords in robot framework

Suppose we have a library for the robotframework with some functions that are more or less the same. For example, there are three keywords set_parameter_a_in_module_b_to_value, set_parameter_a_in_module_c_to_value, set_parameter_a_in_module_d_to_value. Suppose now that we must set all these functions to a specific value for example the value 3.

Then in robot framework we define a new keyword Set Parameter A

1
2
3
4
5
*** keywords ***
Set Parameter A
    set_parameter_a_in_module_b_to_value  3
    set_parameter_a_in_module_c_to_value  3
    set_parameter_a_in_module_d_to_value  3

We can now make the value to be set in a variable and input it as a parameter in the keyword

Read More