Languages

Notes on Golang in one day

September 13, 2020 GoLang, Languages No comments

I’m a Software Engineer with some years of experience in C#, Java, JavaScript and tiny bit of other languages. For fun (I don’t yet need this at work) I spent one day going through GoLang tutorials, this video, and skimming through “The Go Programming Language” book. This blog post is a collection of things in Go that I found to be interesting and worth mentioning. In NO way this can be considered a tutorial or reliable source of information on the language. The best and most comprehensive place to learn about the language is here.

So there you go, golang in 20+ bullet-points:

  • There is shadowing for variables (package level variables can be overshadowed by local scope variables).
  • Package level variables can be exported just based on convention of whether they start with a capital.
  • complex type is a first class citizen type in golang much like int and string.
  • There is a type called “Rune” which is nothing more than Int32 alias to represent characters
  • iota is weird way of incrementing inside of const blocks resetting itself in a new constant block
  • arrays are completely copied on variable assignment b := a, if you want to reference same array you can do b := &a
  • slices are variable length reference arrays
  • there is spread syntax with three dots ... like in some other languages and/or frameworks
  • removing elements from a slice is a funny business requiring you to cut slice in two pieces not containing target element and then concatenating those pieces together
  • To define a map you write something like someMap := map[int]string{1: "one", 2: "two"} and then you get retrieve from it with indication if key exists getOne, ok := someMap[1]
  • You can break out of a parent loop from within nested loop by applying labels to loops.
  • There are no classes or inheritance as such. Closest things to this are struct and composition via process called embedding
  • Execution of code can be deferred. This is quite interesting, as executions is scheduled to the end of function block and if there are multiple defer statements they are unwind in FILO mode, even if there was exception thrown panic.
  • Yeah, there are no exceptions in golang, or better to say, they are not called exceptions but rather panic. Panic can be controlled by recover() function. Probably easiest way to think about this are throw and catch with a caveat that error thrown is not exactly same idiomatically as in other languages.
  • Go is similar to C/C++ as it has pointers, de-referencing, function parameters can be sent by value or reference. Go does not allow pointers arithmetic unless you are using unsafe.
  • Functions support named return values and multiple return values. This is really nice in my opinion.
  • Functions are a bit similar to functions in javascript from usage perspective. They can be immediately invoked and passed around as a param.
  • Interfaces can be applied on any type where you can add methods; they can be composed (just like structs); Go seems to be doing a lot of emphasis on interface segregation.
  • Goroutines combined with channels is probably something most interesting and unique about the language.
  • Goroutine is a thread abstraction, sometimes called “green thread”. They are cheap to create and easy to control. They do not span OS level threads (unless they must, I guess). The way to asynchronously call something is just go getMeADrink()
  • Goroutines can be controlled using waitgroup and mutex. This is standard shared memory multithreading model on very high level similar to other languages.
  • Channels is a way to pass data between goroutines. It can either be a single type or a buffer of things. This is when multithreading can be implemented much differently from other languages. This is also called communicating sequential processes model of multithreading.

I hope this was useful to some of you. For me personally this day gave me some idea what the language is about and the syntax no longer looks alien. Next thing to do would probably be to spend one more day playing with goroutines/channels specifically and actually reading the book for more fun.

Till next time!


No comments


Erlang programming language

December 13, 2012 Erlang, Languages No comments

Erlang logoThe one I didn’t get. But don’t worry, I can “kill” myself and “spawn” another me to try once again.

Not sure if I have to repeat some of the definitions given to this language, because I doubt that my readers read only this blog and never heard about Erlang. But who would start searching for “Erlang” if you are already here, so to avoid this dilemma I just copied one of its definitions later on.

Some of my thoughts

Erlang is great and hard language at the same time. Its syntax easily looks somewhat alien to many developers, not saying about normal people, who are capable of reading only few human languages. On the other hand ideas behind Erlang are just astonishing. “Let it crash” concept works, because there is no shared state between processes, and if something crashes you just restart stuff, not worrying about overhead as processes are lightweight. And how does this sound to you: dynamic language in which you can change code on the fly? I don’t think you can allow for downtime when you are in a rocket. Not sure if NASA uses Erlang, but many telecom companies use it for sure, which resulted in birth of Open Telecom Platform (OTP) – a library for telecom applications.

Why Erlang? – Built to kick ass!

I’ve found following explanation very sensible:

Erlang was developed at Ericsson and was designed from the ground up for writing scalable, fault-tolerant, distributed, non-stop, soft-realtime applications. Everything in the language, runtime and libraries reflects that purpose, which makes Erlang the best platform for developing this kind of software.

Use Erlang if you want your application to:

  • handle very large number of concurrent activities
  • be easily distributable over a network of computers
  • be fault-tolerant to both software & hardware errors
  • scale with the number of machines on the network
  • be upgradable & reconfigurable without having to stop & restart
  • be responsive to users within certain strict timeframes
  • stay in continuous operation for many years

Please visit http://veldstra.org/whyerlang/ for more “why Erlang?”.

How many are there Erlang developers?

This or some similar question often is very interesting when its about some exotic or small language. Hard to answer, but I’ve found this really nice site: http://roberto-aloi.com/languagesintheworld/#. Try it out to figure out who is coding Erlang/Haskell/Scala/… in your country.

Sleeping Barber problem in Erlang

In my Haskell post I wrote “I’m too new to Haskell to talk about some advanced features and to write programs which are over 10 lines of code.” I can ensure that now I can write Erlang programs which are more than 10 lines of code, but I won’t be able to confidently talk about most of aspects of this language either.

I can write larger programs, because I wrote one. Pitfall here is that I don’t completely understand how it works. I believe this is due to the fact, that I’ve chosen wrong problem to solve with this language. Erland is not really build for stuff like “run this for 10 seconds”, but rather for stuff like “that’s your message, deal with it”. Though, I could easily be wrong.

I decided that my first Erlang program will be “sleeping barber” problem, which I’ve already done in Clojure (BTW, there is small bug, spot it!). Once again:

Problem called "sleeping barber." was created by Edsger Dijkstra in 1965. It has these characteristics:

  • A barber shop takes customers.
  • Customers arrive at random intervals, from 10 to 30 milliseconds.
  • The barber shop has three chairs in the waiting room.
  • The barber shop has one barber and one barber chair.
  • When the barber’s chair is empty, a customer sits in the chair, wakes up the barber, and gets a haircut.
  • If the chairs are occupied, all new customers will turn away.
  • Haircuts take 20 milliseconds.
  • After a customer receives a haircut, he gets up and leaves.

Write a multithreaded program to determine how many haircuts a barber can give in 10 seconds.

Mine solution in Erlang

Counter – does nothing smart except of counting number of customers with new haircut

-module(counter).
-export([loop/1,incr/1,get_count/1]).

loop(Count) ->                            
    receive                                   
        { incr } -> 
            loop(Count + 1);              
        { report, To } ->                     
            To ! { count, Count },            
            loop(Count)                           
end.                                      

incr(Counter) ->
    Counter ! { incr }.

get_count(Counter) ->    
    Counter ! { report, self() },
    receive
        { count, Count } -> Count
end.

Barber

-module(barber).
-import(counter,[incr/1]).
-export([loop/0, cuthair/3]).

loop() ->
	receive
	{Pid, Counter}->
		timer:sleep(20),
		Pid ! "haircut done!",
		counter:incr(Counter),
		loop()
end.

cuthair(To, Barber, Counter) ->
	% make barber work synchronously
	Barber ! { To, Counter },
    receive
        BarberService -> BarberService
end.

Barbershop

Crazy stuff. For example, take a look at how I implemented continuous generation of customers. It is tail recursion function, which takes 10000 as starting WorkTime and generates customer after 10-30ms of thread sleeping, then calls itself with WorkTime minus time needed to send customer to barbershop. It continues until function is out of WorkTime. Similar I do for barber_work_day.

-module(barbershop).
-export([loop/3,customers/2,barber_work_day/4]).

loop(FreeChairs, Barber, Counter) ->
receive
	{ customer } ->
		loop(FreeChairs-1, Barber, Counter);
	{ barber } ->
		loop(FreeChairs+1, Barber, Counter);
	{ free_chairs_count, To } ->
		To ! { chairs, FreeChairs },
		loop(FreeChairs, Barber, Counter)
end.                    

barber_work_day(WorkTime, Barbershop, Barber, Counter)
			when WorkTime < 1 -> 1;
barber_work_day(WorkTime, Barbershop, Barber, Counter)
			when WorkTime > 0 -> 
receive
{ start } ->
	self() ! { start },
	X = 20,
	FreeChairs = get_free_chairs_count(Barbershop),
	case FreeChairs of
	_ when (FreeChairs < 3) -> 
		timer:sleep(X),
		Barber ! { self(), Counter },
		Barbershop ! {barber},
		barber_work_day(WorkTime-20, Barbershop, Barber, Counter);
	_ ->
		barber_work_day(WorkTime, Barbershop, Barber, Counter)
	end
end.
	
	
get_free_chairs_count(Barbershop) ->    
    Barbershop ! { free_chairs_count, self() },
receive
        { chairs, FreeChairs } -> FreeChairs
end.

customers(WorkTime, Barbershop) when WorkTime < 0 -> 1;
customers(WorkTime, Barbershop) when WorkTime > 0 -> 
receive
{ start } ->
	self() ! { start },
	X = random:uniform(21) + 9,
	timer:sleep(X),
	
	FreeChairs = get_free_chairs_count(Barbershop),
	case FreeChairs of
	_ when (FreeChairs > 0) -> 
		Barbershop ! {customer},
		customers(WorkTime-X, Barbershop);
	_ ->
		customers(WorkTime-X, Barbershop)
	end
end.

Program

Here I just initialize random, create processes and kick-off generation of customers and barber’s work day.

{A1, A2, A3} = now().

random:seed(A1, A2, A3).

Counter = spawn(fun() -> counter:loop(0) end).

Barber = spawn(fun barber:loop/0).

Barbershop = spawn(fun() -> barbershop:loop(3,Barber,Counter) end).

Customers = spawn(fun() ->
	barbershop:customers(10000,Barbershop) end).

BarberWorkDay = spawn(fun() -> 
	barbershop:barber_work_day(10000,Barbershop,Barber,Counter) end).

BarberWorkDay ! {start}.

Customers ! {start}.

counter:get_count(Counter).

Un-obviously it executes slightly longer than 10 seconds (12-15), so when I call counter:get_count(Counter) exactly after 10 seconds I’m getting slightly lower numbers than expected, so I just call get_count in console until number stops growing with some very realistic number, like 434.

Now you can blame me for my dumbness, because it is really a lot of code for quite simple problem and it took me good 6+ hours to implement.

Links:

I really hope you liked this post! If true, instead of blaming me, you are welcome to share your own experience with Erlang.


No comments


Clojure programming language

November 30, 2012 Clojure, Languages 2 comments

ClojureClojure is a dialect of the Lisp programming language. Accordingly to Rich Hickey, creator of the language, “it is designed to be a general-purpose language, combining the approachability and interactive development of a scripting language with an efficient and robust infrastructure for multithreaded programming.”
Ok, enough! Probably you can read definition and most of the “getting started” information somewhere else. I’m here to share my thoughts on this language and to inspire you to try it out.
Back in university days some of my peers had chance to learn Lisp. (My academic group instead had something else, maybe JavaScript, which I anyway haven’t learnt there.) So I only knew that there is such language as Lisp and it has something to do with lists. Now I know a little bit more – it is about LISt Processing… and I’ve also tried one of its dialects.
Clojure has its differences and some oddness, like, for example, prefix notations. Well, writing (* 5 (+ 2 3) ) instead of (5 * (2 + 3) ) is not difficult, but it is like saying “understand me later you will” in Yoda style! Also having few thousands of “((((“ and “)))))” makes code looking ugly as per me. Or maybe I’m too newbie in formatting source code. Honestly, except of idea that everything is list I didn’t grasp any concept which would sound completely new to me.

Some code

As you may know I’m reading “7 languages in 7 weeks” and for each language there is set of tasks. Initially I thought that I will take the most difficult task from Day 3 and implement it, but when I started coding I realized that it was too hard to be my first program in Clojure. So I took baby steps:
Day 1: Function big that returns true if st is longer than n.

(defn big [st n]
  (if ( > (count st) n) true false))

; usage
(big "is length of this string longer than 15?" 15)

Day 1: Function that identifies collection.

(defn collection-type [col]
       (cond
        (vector? col) (str "vector:")
        (list? col) (str "list:")
        (map? col) (str "map:")))

(collection-type [1])
(collection-type (list 1 2))
(collection-type {:chewie :wookie :lea :human})

Day 2: An unless with an else condition using macros.

(defmacro unless [test body]
    (list 'if (list 'not test) body))
    
(macroexpand '(unless condition body))

(unless (> 1 10) (println "Did you really think that 1 > 10?"))

Day 2: Type using defrecord that implements a protocol.

(defprotocol Person
    (writeName )
    (writeAge ))
    
(defrecord PersonImpl [name age]
    Person
    (writeName [_] (println name))
    (writeAge [_] (println age))
    Object
    (toString [this] (str "Name=" (writeName this) "& Age=" (writeAge this) )))
    
(def andriy (PersonImpl. "Andriy" 25))

(writeName andriy)
(writeAge andriy)
(println andriy)

Hey! Stop scrolling! :)
Day 3: Sleeping barber problem.

So, this is task which I thought I will do immediately after reading about Clojure, but I failed. I was able to perform it after I finished with those above. Here is what I had to solve (as in book):

Problem called “sleeping barber.” was created by Edsger Dijkstra in 1965. It has these characteristics:

  • A barber shop takes customers.
  • Customers arrive at random intervals, from 10 to 30 milliseconds.
  • The barber shop has three chairs in the waiting room.
  • The barber shop has one barber and one barber chair.
  • When the barber’s chair is empty, a customer sits in the chair, wakes up the barber, and gets a haircut.
  • If the chairs are occupied, all new customers will turn away.
  • Haircuts take 20 milliseconds.
  • After a customer receives a haircut, he gets up and leaves.

Write a multithreaded program to determine how many haircuts a barber can give in 10 seconds.

My solution:

(def counter (agent 0))
(def chairs (agent 0))
(def workingTime (agent 1))

(defn haircut [x]
    (do
        (Thread/sleep 20)
        (println "...haircutting...")
        (+ 1 x)))

(defn customer [x]
    (if (< x 3) 
        (do
            (send counter haircut)
            (println "I'm next!")
            (+ 1 x))
        (do
            (println "I went home. This barber shop sucks!")
            (- 1 x))))

(defn waitUntilEndOfTheDay [x]
    (do
        (Thread/sleep ( * 10 1000) )
        (println "[ Clock ticked end of working day ]")
        (dec x)
        ))
    
(send workingTime waitUntilEndOfTheDay)

(while 
    (pos? @workingTime)
        (do 
            (Thread/sleep ( + 10 (rand-int 21) ))
            (send chairs customer)))
            
(println "Barber has finished the day giving " @counter " haircuts.")
I have found many other solutions to this problem, like this one or another by Ben Nadel, or this or even more, but I like mine because it is original and one of the shortest solutions. Plus it has the most interactive output. Like in if you were in barber shop:


…haircutting…
I went home. This barber shop sucks!
…haircutting…
I’m next!
…haircutting…
I’m next!
I’m next!
[ Clock ticked end of working day ]
…haircutting…
Barber has finished the day giving  365  haircuts.
nil

It took me slightly more than one hour of real fun to solve this, but it worth every minute I spent. I like great feeling when something challenging was done. For sure it is one of the components of developer’s happiness.
Have I convinced you that there are a lot of interesting things in programming still awaiting you to pick them up?
Sorry for highlighting. I didn’t find appropriate Clojure highlighter.


2 comments


Haskell programming language

October 29, 2012 Haskell, Languages 3 comments

“Haskell is an advanced purely-functional programming language. An open-source product of more than twenty years of cutting-edge research, it allows rapid development of robust, concise, correct software.” This official definition is only missing one point: Haskell is mind-blowing programming language.

First of all, let’s start with realizing that Haskell is all about purity as opposite to many other functional languages, which do a lot of compromises, like Scala. It could be due to the fact that this language was created by a group of highly educated people, or better to say researches. I think their intent was exactly to create language which would be some kind of definition of a pure functional language.

So what does “pure” mean in this context?

As per Joel Spolsky, when answering similar question on SO:

“In a pure functional language, you can’t do anything that has a side effect.

A side effect would mean that evaluating an expression changes some internal state that would later cause evaluating the same expression to have a different result. In a pure functional language you can evaluate the same expression as often as you want with the same arguments, and it would always return the same value, because there is no state to change.

For example, a pure functional language cannot have an assignment operator or do input/output, although for practical purposes, even pure functional languages often call impure libraries to do I/O.”

Personally I found Haskell to be the most exciting programming language among all I’ve ever touched. It has many interesting paradigms and features. Most of them are present in other languages, some are not. I would like to briefly go through some of them.

Currying

In Haskell there is no function that can accept more than one parameter. What?

Well, of course you can write function

add a b = a + b

But, under the hood it is always translated into 2 functions. One of them is responsible for taking parameter a and applying (+) to result of second function. Second function is there to take first function and apply it on b.

Partially applied functions

This allows for partially applied functions, which is completely cool stuff.

map ( * 2) [1,2,3]

In above code ( * 2) is actually partially applied function. We are only supplying one parameter instead of two, expected by the * function. So the result of what we get is a function like (x * 2), accepting parameter x.

This function is then applied to the list [1,2,3] one by one, thus we get: [2,4,6].

As another example, we can extract partially applied function from our add to create function, which always adds 1.

addOne x = add 1

So it can be used like addOne 5 to produce 6.

Lazy evaluation, zipping and few other things

Lazy evaluation isn’t anything new for C# developer. You can think about it as about differed execution in LINQ. Zipping is not something cool, but rather one of the common features of functional languages, but I just wanted to include it here. Below is function every8, which demonstrates mentioned things as well as ranges and recursion.

module Every8thStartingWithSumOfXandY where
  everyThird x = x:everyThird(x+3)
  everyFifth y = [y,(y+5) ..]
  every8 x y = zipWith (+) (everyThird (x)) (everyFifth (y))

You can later use this code to get [4,12,20,28], like below:

take 4 (every8 1 3)

List comprehensions

This code below allows you two have a list, which consists with items which are less than 3:

[x | x <- [1,2,3,4,5,6], x < 3]

Pattern matching and guars

For example we can match on head and tail of list to perform reverse of list:

rev (h:t) = rev t ++ [h]

Combining pattern matching and list comprehensions we can effectively write quick sort in one line:

qSort (m:r) = qSort [x | x <- r, x < m] ++ [m] ++ qSort [x | x <- r, x >= m]

When I wrote this, I was so much amazed if not shocked about how much Haskell is concise and powerful in expressing complex things. I used to write quick sort many times in C++ back in my university days during programming competitions and even it was easy it never took me one minute or one line to write. (Of course, there are performance considerations regarding two implementations, but we are not talking about them now.)

Monads

Don’t be mislead. A lot of other trivial things in Haskell are painful and difficult to implement. To somehow overcome such complexities concept of monads was introduced in functional languages. With them chain of operations can be executed allowing to bypass some data (or state if you will).  “Haskell is overly abstract and seems to complicate the simplest tasks, but once you see how monads unify some of the most difficult concepts in programming: backtracking, continuations, error propagation, state management, and parsing, among many others, you can begin to appreciate how elegant monads really are. But to people not familiar with those topics and their difficulty and who have never seen monadic code, monads are just weird math crap.” said Tac-TIcs. Well, for me they are still very difficult even I can read and understand code with their usage. I’ve prepared some other piece of code, which will probably not bring much light on monads, but it shows usage of build-in Nothing and Just. Defining own monads is hard, and worth separate blog post.

module Main where

look key [] = Nothing
look key ((k, val):rest)
  | key == k  = Just val
  | otherwise = look key rest

al = [(1, []), (2, [(22, "something deep inside")]), (3, [(33, "else")])]

Which can be used like this:

look 2 al >>= look 22

So you can basically work around Haskell’s restrictions and call methods one by one, using this smarty-looking operator “>>=”. Haskell made easy things hard and then introduced Monads to make those hard things easy again. Now you can write code with sugar do-syntaxes.

Conclusion

I’m too new to Haskell to talk about some advanced features and to write programs which are over 10 lines of code. But from what I’ve tried I definitely like the language. This is language for your weekend’s fun. Play with it!

I hope you liked this short Haskell journey.


3 comments


Scala Language

September 3, 2012 Languages, Scala 3 comments

Back in university I had few classes dedicated to Scala programming language. Sometimes suddenly things come back to us.

If you never heard about Scala, here is my very short introduction.

Scala was created as bridge between object oriented and functional languages so that it can run on Java Virtual Machine (JVM) and be fully interoperable with Java classes. As Martin Odersky, creator of language, said “I wanted to show that the two paradigms can be unified and that something new and powerful could result from that combination.”

Scala doesn’t force to write in functional style, however it does have all standard features one would expect from functional programming language. The more you prefer OOP, the more likely that your Scala code will look like Java code. If someone starts with functional languages he or she might get impression that Scala isn’t functional language at all. Personally, if I wanted to learn functional programming I would rather go for Haskell which will “force you to eat the whole functional programming burrito”, as Bruce A. Tate, author of “7 languages in 7 weeks” says.

Scala allows for very laconic syntaxes. Sometimes it is way to much of different syntaxes, sometimes syntax is quaint, for example operator “::=” for adding elements to the list, but once you played enough with language you will be able to write shorter pieces of code than what it would take in most conventional languages.

Here is how you could calculate total sum of string lengths in a list:

val listOfStrings = List("a", "ab", "abc", "abcd")
val totLength = (0 /: listOfStrings) { (length, item) => length + item.length() }
println(totLength)

I also wrote generation of permutations in in lexicographic order:

object PermutationGenerator extends App {

  var perm = Array[Char]('a', 'b', 'c', 'd')
  printPerm(1, perm)

  for (i <- 2 to factorial(perm.length)) {
    perm = nextPermutation(perm)
    printPerm(i, perm)
  }

  def factorial(n: Int): Int = n match {
    case 0 => 1
    case x if x > 0 => n * factorial(n - 1)
  }

  def printPerm(i: Int, a: Array[Char]) {
    print(i + ": ")
    a.foreach(c => print(c))
    println()
  }

  def swap(a: Array[Char], i: Int, j: Int) {
    val tmp = a(i)
    a(i) = a(j)
    a(j) = tmp
  }

  def nextPermutation(a: Array[Char]): Array[Char] = {

    val k = (a zip a.tail) lastIndexWhere { case (x, y) => x < y }

    val l = a lastIndexWhere { c => a(k) < c }

    swap(a, l, k)

    return a.take(k + 1) ++ a.takeRight(a.length - k - 1).reverse
  }
}

Code above isn’t functional or imperative completely but rather some combination. Scala is different from other languages, because it allows for such flexibility. There are languages which make easy things hard and hard thing easy. In Scala it is up to you. For example, to avoid swap method (mutable operations) I could have wrote this “obvious” statement:

return (a.take(k) :+ a(l)) ++ ((a.takeRight(a.length - k - 1).take(l - k - 1) :+ a(k)) ++ a.takeRight(a.length - l - 1)).reverse

Few days ago I also wrote one application to continuously traverse web site and find there some specific links and then send e-mail with complete list of them. But to be honest I gave up debugging it and finding problems, even Scala has more or less accepted integration in eclipse IDE. App was rewritten in C#. My cheating was supposed to win T-shirt to my wife. Surprisingly the site went down next day. My guess is I was not the only one smart-ass to do traversing of the site.

I only took few baby steps, but from what I know now I feel deep sympathy to this language.

Links:

How and Why Twitter Uses Scala

Scala official introduction

Have you every programmed in Scala? How was it?

I imagine that it was fun, but would like to hear from you.


3 comments


Io programming language

July 8, 2012 IoLanguage, Languages 6 comments

I would expect that most of you never heard about such programming language as Io. Very likely programmers would associate Io with “input-output”, but Io language has nothing special to do with it and has no cool in-out features.

Io is extremely tiny language which runs on supermall virtual machine, even your micro-oven can handle. Having that said I don’t mean that Io is not powerful.

Io is prototypical object-oriented language with dynamic typing. For me, as C# guy, it was not easy to “feel” the language. I could very quickly understand syntaxes and mechanisms of language. It will not take for you longer than 20 minutes to start writing simple code, either. I was understanding what I was trying out, but I didn’t feel myself comfortable with realizing that anything can be changed in this language on the fly which could affect all of the prototypes of changed object. Note that there is no difference between class and object, or better to say, there are no classes in Io. If you define method on some object it is ultimately inherited to the clones. It worth to mention that in Io every operation is message. “Hello world” application which would look like:

“hello world” println

Should be understood like: “send message “println” to the string object”.

Here is bit more code (sheep example cloned from this post):

Sheep := Object clone
Sheep legCount := 4
MutantSheep := Sheep clone
MutantSheep legCount = 7
dolly := MutantSheep clone
MutantSheep growMoreLegs := method(n, legCount = legCount + n)
dolly growMoreLegs(2)

The coolest thing about Io is its concurrency model, at least I think so.

Io uses coroutines, actors, yielding and future stuff. If you don’t know what it is about. Here is a bit of explanation. Coroutines in Io are user threads, built on top of kernel threads, which allows for quick switching of contexts and more flexibility in general. For simplicity think about coroutines as about threads. Any object can be sent message asynchronously, by adding @ symbol before the message name. This message is then places in object’s message queue for processing. Object would hold coroutine (thread) for processing those messages. Objects holding coroutine are called Actors. Effectively any object in Io can become Actor. When you call some methods asynchronously, result can be saved into so called “future”, value of which is resolved before it is used. You can switch between actors using “yield”. To demonstrate this, I prepared this small piece of code, which prints numbers 0,1,2,3 one by one:

oddPrinter := Object clone
evenPrinter := Object clone
oddPrinter print := method(1 println; yield; 3 println; )
evenPrinter print := method(0 println; yield; 2 println; yield)
oddPrinter @print; evenPrinter @print;

If you found this to be interesting I recommend you to read Io Guide. There you will find many other interesting features of the Io language, which I didn’t mention.

Here are some links:

You may be wondering why I’m writing and learning something about old, small language, which even doesn’t have normal ecosystem.

I’m trying to learn more programming concepts and play with different languages. Recently I was even blamed for writing “enterprise-y code” and suggested to see how code looks like in other programming language communities. Well… of course it is valid and good suggestion, but not that I never thought about it. In my year plan post I mentioned that I would like to learn one more programming language and to start with something I picked up interesting book called “7 languages in 7 weeks”. So far I read and tried Ruby, Io and Prolog. Scala, Erlang, Clojure and Haskell are next in a row. After I’m done with book I will pick one language (not compulsory from list) and extend my knowledge in it. Of course there will be a review on the book.


6 comments


Існує die Frage of Language. Или нет?

April 23, 2012 Languages, Opinion 6 comments

Question of Languages Blog Post Cloud

Title of the post is complete bizarre(*). It consists of words out of 4 languages I have to deal with now.

Before I moved to Austria I mostly used Ukrainian. Of course, many meetings at work were in English and all mailing was held in English. Not to mention, there was some interaction with Russian, but not much. At least there were no real need to speak it. Now everything has shifted. I knew that I will have to deal with English everyday, I also knew that I will need some basic German. What I did not know is that there will be many guys from Ukraine and Russia at work and I will use Ukrainian and also Russian for small talks in kitchen or at lunch or for one-to-one discussions.

I continue to speak Ukrainian at home with my wife. We try to use English/German phrases. My wife is not good in English, instead her German is at intermediate level, so we try to exchange some knowledge in languages. But you know what? Unless someone or something kicks you in the ass, you won’t take learning of language seriously.

So, I paid 290 euro to have someone kicking me each day for 2 hours during whole month. Normally it is called language course. After one week I can introduce myself and provide brief information about myself, I can count and ask basic questions, I already know some colors, week days, months, restaurant words, etc.

It worth to mention, that you really need some pressure to start learning German in Austria, because all people around speak English very good and if you are lazy you can simply avoid conversations in German. Plus everything here could be done via internet or though automatic devices, so not much human interaction during the day.

I’m afraid for foreigners coming to Ukraine for EURO 2012. On average people don’t speak English in Ukraine. It is pity and shame for me.

Now back to German language courses. As I mentioned, I’m attending intensive evening courses for total beginners. I allocate myself 1 hour before class to do my home work. So in total it is 3 hours of German per day. My group is rather small – only 4 people, me and one girl from Ukraine, lady from Kazakhstan and another girl from Iran. If there are some explanations needed they are provided in German, if not understood in Russian or English (only girl from Iran doesn’t understand Russian). Another very interesting thing is that, as school is concentrated in Russian/German, teacher is not extremely good in English. Thus I often help to explain things to girl from Iran who is proficient in English. For me it is great – I hear explanations twice: in English and Russian.

To your surprise there are many words which sound similar to English and some are similar to Russian and Ukrainian words (or probably otherwise). Germany/Austria geographically are located between Great Britain and Russia/Ukraine so it could be understood without reading dozen wiki pages on language families, branches and their roots. Again, good for me.

Nevertheless, I have this question: “Is German important language anyway?” Accordingly to wiki there are about 100 millions German speakers in the world, so 12th place by number of speakers, but apparently it is number one in Europe where I live now. It is highly developed language, it is also language of technology (after English of course). All these sound great and everyone would answer that German is important language for Europe, especially if you already know English. So would I. In short term it makes sense to learn German. But in centuries world will dramatically shift to English, if not Chinese.

This all makes me think about importance of languages, their meaning for me and their value for world. Imagine there are no other languages, but just one, no matter which, how much would world be easier? The most importantly, how much further would we develop? Would we already start to colonize Mars? Or would it have opposite effect? Accordingly to Darwin there should be some deviation, otherwise no evolution could be progressing. All these are very philosophical questions and suitable for beer evening, or… for Friday snaps evening.

To conclude, I’m very proud to realize I will understand almost 1 billion people in the world after I learn German (precisely, 902 millions as per wiki).

I have some questions for you:

  • What languages do you know?
  • Do you learn any?
  • Do you think English is number one language and there is no sense to learn and develop other languages?
  • Would you learn German if you were me?
  • Do you think it is possible to be high in IT/Software industry for not native speakers of English?

Thank you!

P.S. Hope this was good reading. If not, please let me know. I’m willing to improve my blogging skills to write posts of higher quality. All for you.

(*) In English it would be “There is question of Language. Or not?”.


6 comments