First days in Delsbo

3 days ago me and my family went on our yearly holiday trip to the place where my father is from. Every year we go to this place called Delsbo in Hälsingland where my grandmother and most of my other relatives on my fathers side. It was a great feeling being back again. These 12 hours I spent in the car together really paid off. Every time I come back It feels like I’m home. I see mountains. I see a lot of forests and lakes. Something quite rare back in Scania.

Dellenbygden
Dellenbygden

The weather has been great so far, a bit to great. It has taken some time to adapt to the warmth. But today It has been quite a enjoyable day. Neither cold or hot. I went swimming in Sördellen, one of the great Dellen lakes. The temperature in the water was about 22 deg. Celsius. I later spent the evening with some relatives.

Tomorrow (Sunday, July 5) it is spelmansstämma at Delsbo forngård, a kind of museum. A lot of folk musicians are coming to play traditional folk music. People come and meet new people and also experience a bit of the culture of this area.  One of the things that a visitor should not miss is ostkaka (lit. cheesecake). It is indescribable for those who haven’t tasted it. If you are from Delsbo or any other town you may wear your own traditional regional costume. Delsbo has its own and almost everyone here has got one which they wear at special occasions. The spelmanstämma  has been held for more than a 100 years now, and it is well known around the country.

The spelmansstämma (musician gathering) is held every year in the first weekend of June. There is a couple of other events like this. Another very popular is the one in Bjuråker two weeks from the one in Delsbo. It is a larger event than Delsbo, which is the oldest.

Delsbo is a average town located at the southwest shore of Sördellen, the southern lake. It is about 30 kilometers to Hudiksvall, the nearest big town. There’s a school (elementary and upper) and there’s two supermarkets. Normally it does not seem to be much life in this town but in the summer it becomes flourishing because of the summer residents.

Delsbo
Delsbo

I would like to return to the Dellen lakes. That is a landmark which also has given the town its name. The lakes form a lake system originally created when meteorites fell down on Earth. Due to volcanic activity in the ground a special type of rock was created from the lava which came from the ground. It is called Dellenite. There are two types of it: the red one from the southern lake and the black one from the northern. The Dellenite has become the national rock type of the whole province of Hälsingland.

Norrdellen (view from Avholmsberget)

I really like being back in Delsbo and I think this summer will be at least as good as the ones I have spent here before.

Dynamic typing in C#

As I wrote in the previous blog post about the Dynamic Language Runtime (DLR) some of the statically typed general purpose programming languages already available on the .NET platform will contain constructs which makes it easier for them to interoperate with the DLR and the languages upon it. In this article I will introduce you to the new features in C# 4.0, and the new dynamic type which brings dynamic typing to the language. I will try to explain what really happens under the hood.

The code examples I will be showing are supported by .NET Framework 4.0 Beta 1. Feel free to download it here at Microsoft’s website. Visual Studio 2010 Beta 1 can be downloaded at the same location.

Dynamic type

In C# 4.0 you are being introduced to the new dynamic type. Some may wonder why somebody would like to add something that would break the type-safety of the language. But if you learn more you realize that a variable of type dynamic is statically typed to be dynamic at runtime. That means that the type of the variable does not change but the type of its contents does. It will forever be dynamic and be able to hold any type of object.

dynamic x = "Hello, World!";
x = 2;  //Valid because it is of type "dynamic".


The current type of the object held by the dynamic variable is unknown at compile-time and will always be resolved at runtime, hence if you make a call to a method it the compiler would not complain if it turned out to not be a valid action.

dynamic foo = "foobar";
stringstr = foo.ToUpper();

foo.Bar(); //Not a member of String. Runtime exception.


As seen in the next example the dynamic type will automatically try to cast its object if you try to assign it to a variable typed other than dynamic.

dynamic foo = "foobar";
string a = foo;  //Will pass this.
int b = foo;  //Will fail at runtime.

As seen in these examples dynamic is a type that is handled at runtime.

There are no checks at compile-time which makes it an unsafe type to use.

It is best not to use it for other than interop with dynamic programming languages like IronPython. So it is not a type you would normally use in C#.

It is preferred that you stay with your old habit of static typing.

Note: Visual Studio will not provide any IntelliSense for dynamic variables because the type is uncertain before runtime. The same with member calls.

VS cannot be sure of the type before it is executed. If you are using Javascript in you will not find this so surprising.

Behind the scenes

Now to the most interesting part. What does the IL that is generated by the compiler look like? Let us dive into it.

We have this program:

dynamic A = 42;
Console.WriteLine(A);

This program actually does nothing that is useful. It only assigns the value 42 to

the variable A of type dynamic and then prints it out with a call to Console.WriteLine.

This is the disassembly in .NET Reflector:

object A = 42;
if (<Main>o__SiteContainer0.<>p__Site1 == null)
{
    <Main>o__SiteContainer0.<>p__Site1 = CallSite<Action<CallSite, Type, object>>.Create(new CSharpInvokeMemberBinder(CSharpCallFlags.None, "WriteLine", typeof(Program), null, new CSharpArgumentInfo[] { new CSharpArgumentInfo(CSharpArgumentInfoFlags.IsStaticType | CSharpArgumentInfoFlags.UseCompileTimeType, null), new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null) }));
}
<Main>o__SiteContainer0.<>p__Site1.Target(<Main>o__SiteContainer0.<>p__Site1, typeof(Console), A);

As seen you actually assign 42 to a variable of type object. The variable will therefore be able to contain a reference to any kind of object, because every object inherits from the .NET base class Object.

What is not quite obvious is the calls done under that first line of code.

This code interacts with the DLR and makes it possible to resolve and do safe calls at runtime instead of compile-time, which is the usual way in C#.

The DLR is using CallSites to be able to resolve members at runtime.

CallSites

A CallSite is a type that performs lookups on members called dynamically at runtime. It can be a call to a member of a dynamic variable. In that case it is impossible to know at compile-time if it really exists. CallSites automatically checks if the action is valid.

In our disassembled code it first checks if the CallSite has been initialized, else it initializes it with a CallSite that functions as an member invoker.

It is set to work with the method we want to call, Console.WriteLine. Our argument is dynamic and we have to see if its value can be passed to any of its overloads. This is performed at the last line where the argument is passed into the DLR. If this is invalid the DLR would throw a runtime exception.

This is kind of silly here because Console.WriteLine takes object as an argument in one overload so this does not make any good use in this example.

In the assembly generated by the C# compiler you will find that CallSites live in a nested static class named something like <Main>o__SiteContainer0.

CallSites are simply static fields of the generic CallSite<T> class.

[CompilerGenerated]
private static class <Main>o__SiteContainer0
{
    // Fields
    public static CallSite<Action<CallSite, Type, object>> <>p__Site1;
}

Now where going to view one last sample. This time we call an object member.

We compile the code and then disassemble it for study.

dynamic A = "Test";
string r = A.ToUpper();

This is what .NET Reflector gives you:

object A = "Test";
if (<Main>o__SiteContainer0.<>p__Site1 == null)
{
    <Main>o__SiteContainer0.<>p__Site1 = CallSite<Func<CallSite, object, string>>.Create(new CSharpConvertBinder(typeof(string), CSharpConversionKind.ImplicitConversion, false));
}
if (<Main>o__SiteContainer0.<>p__Site2 == null)
{
    <Main>o__SiteContainer0.<>p__Site2 = CallSite<Func<CallSite, object, object>>.Create(new CSharpInvokeMemberBinder(CSharpCallFlags.None, "ToUpper", typeof(Program), null, new CSharpArgumentInfo[] { new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null) }));
}
string r = <Main>o__SiteContainer0.<>p__Site1.Target(<Main>o__SiteContainer0.<>p__Site1, <Main>o__SiteContainer0.<>p__Site2.Target(<Main>o__SiteContainer0.<>p__Site2, A));

There are two CallSites in this code. The first one is a converter and the second is a member invoker. The action is performed on the last line of code. It involves the lookup and the call to the the member ToUpper. The result is converted to a string and stored in the string variable r.

If you want to check out these features you got to download Visual Studio 2010 Beta 1.

Wakoopa

Wakoopa is a social network site which keeps track on what software its members use. I find it a very useful to keep track of what applications I and others use daily. The tracker records the usage of programs, games and web apps and send it to your profile.

To start using Wakoopa you simply sign up, download and install the tracker that is available for Windows, Mac OSX and Linux.

This is my profile.

Here’s my latest top 10 software list:

Software tracking

Dynamic Language Runtime

The Dynamic Language Runtime (DLR) is Microsoft’s effort to bring dynamically typed programming languages to the .NET Framework platform. It has been around for some time now and is being improved now as I write. Currently it is version 0.91. This article aims to be a short introduction to the concepts of the DLR and the programming languages that are dependent of it.

The DLR is actually a runtime library which forms a layer upon the static Common Language Runtime (CLR). It relies heavily on reflection to create code that can be executed dynamically during runtime. So there are basically no changes to the CLR, just a layer of libraries making things seem to be carried out dynamically and then being able to work with other statically typed programming languages like C# and VB.

DLR defines these:

The DLR is built upon the idea of having an abstract syntax tree with expression nodes that are used to dynamically generate the corresponding code at runtime. The compiler of any dynamic programming language that is built on the DLR is generating these DLR abstract syntax trees which later is executed by the DLR libraries.

DynamicSite objects are caches contained in the assembly that are dynamically updated at runtime. Dynamic sites contains objects which points to methods for a fast lookup of their signatures at runtime. The invocation must check if a call is valid and if so bind it to the actual implementation of the method.

.NET Framework 4.0 will be the first release to contain the DLR libraries. You can download and try .NET Framework 4.0 Beta 1 along with Visual Studio 2010 Beta 1 from MSDN.

Microsoft has released the DLR under Microsoft Public License which is an open source license which allows anybody to redistribute it in their own project. That allows the Mono Project to bundle it with their future releases.

Dynamic programming languages

Moving on to the programming languages . The DLR makes it easier to implement dynamic programming languages as Python and Ruby, through IronPython and IronRuby, on the .NET platform. Defining a shared library which makes interoperability between them and the rest of the static languages possible. They have binders to both the CLR and the native main implementations.

IronPython is an open-source implementation of Python running on the DLR. It allows Python program to run and take advantage of the .NET Framework. There are binders to various platforms like CPython and the CLR. It also works with Silverlight (2.0 and above).

The project was initially started by Jim Hugunin, who previously wrote Jython (formerly JPython), the Java implementation of Python. Hugunin wanted to see if Python could run well on the .NET Framework and therefor he started writing IronPython. He thought that it would be inefficient but was rather surprised when it turned out to run very well. Later he was hired by Microsoft as a developer where he took the initiative to create the Dynamic Language Runtime. Since then he has been the leader for both the DLR/Iron Python-team.


from BookService import BookDictionary

booksWrittenByBookerPrizeWinners =
[book.Title for book in BookDictionary.GetAllBooks() if "Booker Prize" in book.Author.MajorAwards]

Likewise there is an implementation of Ruby called IronRuby. It has the same goals as IronPython and the original project called RubyCLR was started by John Lam, who now works as a Program Manager at the DLR Team. Initially it was just a binder to Ruby but it has evolved and is now a open-source project at Microsoft.


sb = StringBuilder.new
sb.Append "Hello"
sb.Append " World!"
puts sb.ToString

Because of their open-source nature both languages run on Mono as well although there are no guarantees they will not do it as IronPython and IronRuby currently are under development.

There are other language implementations as well. Managed JScript and IronScheme among others.

From version 4.0 Microsoft’s implementation of C# will support dynamic typing through the dynamic keyword which makes it easier to interop with DLR languages and COM objects. Visual Basic 10 will have similar functionality with the Dim keyword. Mono will also add this soon. How this really works under the hood will be something to talk about in another blogpost.

Note:

Sun is currently working on a new version of the Java Virtual Machine, called the “Da Vinci Machine”, which adds support for dynamic programming languages to the Java Platform at runtime level. New op codes are being introduced to the instruction set of the Java Bytecode.

The computational knowledge engine

Two months ago the math-oriented company Wolfram Research launched their new “search engine” Wolfram|Alpha. I write it in quotes because it is even more than just a search engine, it is what they would call a computational knowledge engine.

It is a web service that is based on the company’s flagship Mathematica. Using it as the back-end when processing all the data to get a statistically accurate answer. Unlike search engines like Google and Bing, which only search the web, Wolfram|Alpha has a wider range of functionality. It allows you to get data, statistics on for instance the US, calculate mathematical expression and then plotting them… and yes more.

Here’s some samples:

x^2 + 4x – 1

plot x^2 + 4x – 1

population of the US

sphere, volume = 5 dm^3

Stockholm

Methane

IBM Microsoft

weather Madrid

Michael Jackson

2% of $200

You can write even more advanced queries. Request IP-number lookup and more.

Try it yourself at WolframAlpha.com.

Wolfram|Alpha do not wish to compete with the other search engines that queries web sites.

Lexical scanners

How do a scanner work then? Is it hard to write one by hand? I will show you and no it is not.

Let’s start with theory.

A scanner is a finite state-machine, or more precisely a Deterministic Finite-state Machine (DFSM). It handles different states through regular expressions. In this case it maps the characters in the input stream to the rules. Do not worry if this does do not make sense right now.

The DFSM has a starting state and from that you may fulfill some conditions to reach another state, and another from that. If there are no condition that can be satisfied you simply go back to the initial state.

We will take a look at this example where we have a string: “foozie30 23.3″. A valid DFSM for this input could be drawn like this:

dfa

The most common ways of implementing this state machine in an imperative programming language would be using state controllers like if, while and for or any equivalents. You process each character and when you got the string you return an object of a type which symbolizes the symbol that was found. In an object-oriented language it would be even simpler to implement if you ask me.

If you want to take a look at an implementation you just download my Expression parser project. :)

Most compiler geeks, as they are called, are using parser generators and grammars that create both scanner and parser. A parser is far more advanced than scanner. It is not impossible to write them by hand, as I have shown, but generally it is regarded as better writing a grammar and then let the generator create the scanner and the parser for you.

Compilers are very interesting both in theory and in their implementations. Because it is such a large subject you will probably not find this enough. That is why I am planning to write more articles about compilers and techniques that can be used while writing one.

The dynamics of Dynamic programming languages

One of the things that fascinates me when it comes to programming is the underlaying architecture which allows programs to be executed on your computer. I think it is interesting to know how data is handled. There are many ways of handling data. Usually all the data has got a type bound to it. That means that if we have a value then it must be of a type to ensure some kind of safety at runtime. You declare a variable of type int and it will forever, in the liftime of the program, be a variable of that kind. The compiler will automatically cast an error if you assign a string of character (text) to the it. This is called static typing.

In difference to this there is a concept where you do not need to think of types in this way. In most dynamic programming languages variables do not have fixed types and you can therefore assign what kind of value you want to it. The type will change to the one of the new value at runtime. And to say there are implicit conversions between different types and you do not have to worry about if you want to cast an int to a double or vice versa. This is called dynamic typing. It will be done without any extra effort from you. So the languages are still type aware in a manner. I will now talk more about ideals type-safety. You need to be aware of languages and their differences. I will later mention the behaviours of PHP and its flaws.

Type-safety is a lot. In static programming (the first part) you have the notion of variables with fixed types, and that is an implementation of type-safety. But there is so much more. You do not need to have typed variables to be a lot less than that. Type-safety is also about having a set system where you get the behaviour you want and prevent the unwanted from happening. Many traditional programmers prefer static typing and what it gives because you are guaranteed to write less buggy programs and then execute them “safely”. On the other hand, an experienced programmer may also use a dynamic language despite this and produce safe code without the safety provided by static typing. It depends on the programmer, and of course the underlaying runtime which hopefully protects you from doing things fatal to your system.

All languages are either classified as strongly- or weakly typed depending on their way of handling the types of data. That is regardless of whether it is a statically typed language or not. PHP is an example of a weakly typed language.

Productivity is said to be larger with a dynamic programming language than with a typed because you do not really care about types as much in static, non-dynamic languages, like C, C++, C# and Java. You are then simply concentrating at the algorithms and logic, and not the types of the objects.

Now let us continue with type-safety. PHP is for instance not a very type-safe language (weakly typed in other words) because you may do what ever you want and the runtime will not complain but do exactly what you wrote, unless it is syntactic or logical. If you add a boolean value (true or false) with a number you will probably add them as a number. If you just want to add these as a string you may have to write some more code. But because PHP is a scripting language you may try as you write to find errors in your code. There is usually no way of becoming aware of them when writing the programs, or scripts. Errors are deteced at runtime in the realm of dynamic programming languages.

This tells you that runtime is what matters in dynamic languages, opposed to compile-time which is important in many statically typed languages. That is why very few dynamic languages needs to be compiled before execution. It is carried out on the fly when entering it in the console. Reflection and runtime alteration are usually a feature of the most renowned languages. Everything happens at runtime, baby!

Another dynamic scripting language is Python. It is regarded as one of the most popular of its kind. There is a significant difference in the way it handles types, as in any framework of a programming language. No programming language has the same architecture. Many share similarities though. Python is truly a scripting language and the fact that it comes with an interpreter really confirms that.

The interpreter allows you to type code in a console. The code will then be executed on the fly, dynamically! This is common for many scripting languages. It gives developers a way of really try as they write.

Other features common to dynamic programming languages are support for functional programming. Most of the concepts initially derive from LISP.

So there are many advantages and disadvantages with dynamic programming languages, like all programming languages. I do not want to argue about which one is the best. I think that programming languages shall be chosen by need, and then it is up to the programmer, YOU, to use it right. As a developer you always have to adopt new ways and new techniques to be up to date in a constantly changing world of bits and bytes, data.

Thanks for reading.

Welcome to my blog!

Hello and welcome to my blog!

I am very pleased to announce that I have returned and that I am updating the blog. You can now read my resumé and CV is also available on the About page. If you are interested in my work you may check the Projects page.

I hope to write about more interesting things now when I am attending college this fall. But that depends on how much time I get while studying.

Stay tuned!

/Robert

Student i en klass för sig själv

Publicerad: 9 juni 2009, 01:15

 

Ystad
Robert Sundströms framtid stavas programvara. På fredag blir det studentavslutning vid John Bauergymnasiet. Och handledaren på IT-linjen är smått lyrisk över hans talang.

– Robert har gjort ett mycket avancerat projektarbete inom programmering. Nivån ligger långt över vad som kan förväntas, mycket hög klass, säger utbildningsansvarige Karl-Erik Bolin.

Den 19-årige avgångseleven uppfyller de viktigaste kriterierna med råge, menar han.

Brinnande intresse

– Man måste kunna bolla med språket, man måste vara analytisk och kunna bryta ner problemen i beståndsdelar och helst ha ett brinnande intresse för datorer och programmering.

Robert Sundströms projektarbete består av en kompilatorkonstruktion, eller ett översättningsprogram, som omvandlar förståeligt språk till maskinspråk med matematiska uttryck och maskinkoder.

Robert Sundström är bosatt i Hammenhög, men i höst flyttar han till Ronneby och studier vid Blekinge tekniska högskola.

– Sen hade det varit kul att få jobba vid ett större företag inom programvarubranschen, säger den avgående gymnasten till YA.

Magnus Wegerup

En kommentar länkar till ett inlägg på bloggen till Programvaruteknik (PT)  på BTH. Tack så mycket Mikael Roos, programansvarig på PT, för det här uppmärksammandet!

PC or Mac?

PC or Mac? That is the question. I would like to clear some things up. The term “PC” is generally used when talking about computers with Windows or Linux operating systems. But the fact is that it includes all computers running operating systems built for the consumer market, including Mac computers. However, Apple has always wanted to classify their own computers as a separate and unique type of computers because their computers (both hardware and software) are entirely put together by them. It is all about their brand, Mac(intosh), a brand of PCs.

Another misconception is that PC includes computers only based on the popular x86 and x64 architectures. That is also false even when talking about Apples old PowerPC architecture, which is now by the way replaced by the others.

Apple! You are PC and you better start compete as PC.

The correct terms are Windows and Mac!

Next Page »




Robert Sundströms Facebook-profil

Tweets

Recent Comments

wilhol on PC or Mac?

Categories

Calendar

July 2009
M T W T F S S
« Jun    
 12345
6789101112
13141516171819
20212223242526
2728293031  

Blog Stats

  • 13,307 hits