All examples except gpseq are run and compiled with the vala filename command.vala
Std
Std means GLib
Hello world
print ("hello, world\n"); //If you don't need to allocate memory in the heap then main is not needed
User Input
stdout.printf (@"Your name is : $(stdin.read_line ())");
Mathematics
stdout.printf ("Please enter the radius of a circle: ");double radius =double.parse (stdin.read_line ());stdout.printf ("Circumference: %g\n",2*Math.PI* radius);stdout.printf ("sin(pi/2) = %g\n",Math.sin (Math.PI/2));
Environment.get_current_dir();Environment.get_real_name();Environment.get_system_config_dirs();Environment.get_user_config_dir();Environment.get_application_name();Environment.get_home_dir();...//Windows specificWin32.is_nt_based();Win32.OSType.SERVER;//enumWin32.get_windows_version();Win32.getlocale();Win32.get_package_installation_directory_of_module(hmodule);//hmodule is pointer...//Linux specificLinux.Network.ifMap.port;Linux. anything from linux.h;
Network
Get Twitter Status
Soup Library
usingSoup;voidmain () { // add your twitter usernamestring username ="gnome"; // format the URL to use the username as the filenamestring url ="http://twitter.com/users/%s.xml".printf (username); // create an HTTP session to twittervar session =newSoup.Session ();var message =newSoup.Message ("GET", url); // send the HTTP request and wait for responsesession.send_message (message); // output the XML result to stdout stdout.write (message.response_body.data);}// to run: vala --pkg libsoup-2.4 filename
publicclassSignalTest:Object {public signal voidsig_1(int a);stringto_string(){ return"hello from SignalTest\n";}}//The first argument is always the object that caused the signal.voidmain() {var t1 =newSignalTest();t1.sig_1.connect((t, a) => { print(@"$a $t\n"); });t1.sig_1(5);}
Native Regular Expression Literals
string email ="tux@kernel.org";if (/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.match(email))stdout.printf("Valid email address\n");var r =/(foo|bar|cow)/;var o =r.replace ("this foo is great",-1,0,"thing");print (o);//this thing is great
Class
Классы выделяются на куче.
Memory for classes is allocated on the Heap.
Things u can do with classes:
classKlass{publicint a {privateset; owned get; default = 3;}// propertypublicint? b =3; //? means it may be null|=3 same as default = 3publicstring c;public inline voidhello() {print("Hello");}//inline signal voidsig_1(int a);// Event with datapublicKlass(){print("usual constructor\n");}public Klass.with_a(int _a){a = _a;}//named constructor}voidmain () {var klass1 =newKlass(){a =5, b =6, c ="param named constructor"};var klass2 =newKlass.with_a(5);}
owned get means that the object will own the link after the transfer, that is, it is like move semantics in C++
In Vala, as in Go, there is no function overload, but you can use named constructors and default arguments
В Vala как и в Go нету перегрузки функций, но можно использовать именованные конструкторы и аргументы по умолчанию
On the 11th line, you can see the creation of a class with some arguments specified without a constructor. This is similar to named function arguments.
На 11той строке вы можете увидеть создание класса с заданием некоторых аргументов без конструктора. Это похоже на именованные аргументы функций.
Gpseq (C# Linq/Java Stream API, Go lang Chanels and Parallelism)
Parallel sorting
Gee.List<int> list =Seq.iterate<int>(9999, i => i >=0, i =>--i) .parallel() .order_by() .collect( to_list<int>() ) .value;for (int i =0; i <5; i++) {print("%d ",list[i]);}
usingGpseq;voidmain () {int[] array = {1,2,3,4,5,6};Channel<int> chan =Channel.bounded<int>(0);run(() =>sum(array[0:array.length/2], chan));run(() =>sum(array[array.length/2:array.length], chan));print_sum(chan);}voidsum (int[] arr,Sender<int> ch) {int sum =0;for (int i =0; i <arr.length; ++i) sum +=arr[i];ch.send(sum).ok();}voidprint_sum (Receiver<int> ch) {int left =ch.recv().value;int right =ch.recv().value;print(@"$left $right $(left + right)\n");}//result = left: 6(1+2+3) right: 15 left+right: 21
GoLang like Managed Blocked Parallelism
constulong SEC =1000000;TaskEnv.apply(newCustomTaskEnv(), () => {Seq.iterate<int>(0, i => i <100, i =>++i) .parallel() .foreach(g => {blocking(() => {Thread.usleep(1* SEC); }); }) .wait();});
If you comment out the blocking block and put only Thread.usleep then the program will run for a time equal to the number of running threads divided by the number of threads of your processor.
With blocking, it is equal to the execution time of a single thread, that is, one second. This is called work stealing. When a thread starts waiting for something, such as a packet from the network, another thread steals its CPU time and starts working until the first thread waits for the event it needs.
Если вы закомментируете blocking блок и оставив только Thread.usleep, то программа будет работать в течение времени, равного числу запущенных потоков, деленному на число потоков вашего процессора.
C blocking оно равно времени выполнения одного потока, то есть одной секунде. Это называется work stealing. Когда поток начинает чего то ожидать, например пакета из сети, другой поток ворует у него процессорное время и начинает работать, пока первый не дождется нужного ему события.
GObject
3 Types of classes
Vala supports three different types of class:
GObject subclasses are any classes derived directly or indirectly from GLib.Object. This is the most powerful type of class, supporting all features described in this page. This means signals, managed properties, interfaces and complex construction methods, plus all features of the simpler class types.
Fundamental GType classes are those either without any superclass or that don't inherit at any level from GLib.Object. These classes support inheritence, interfaces, virtual methods, reference counting, unmanaged properties, and private fields. They are instantiated faster than GObject subclasses but are less powerful - it isn't recommended in general to use this form of class unless there is a specific reason to.
Compact classes, so called because they use less memory per instance, are the least featured of all class types. They are not registered with the GType system and do not support reference counting, virtual methods, or private fields. They do support unmanaged properties. Such classes are very fast to instantiate but not massively useful except when dealing with existing libraries. They are declared using the Compact attribute on the class, See
Memory for Compact classes is allocated by this monster.
//The slowest class. //Supports introspection of property and functions as well// as thread-safe signals to property.publicclassGObjectKlassExample:Object {}publicclassGTypeKlassExample{}[Compact]publicclassFastestKlassExample {}
Run-Time Type Information
bool b =objectisSomeTypeName;// run time type checkType type =object.get_type();// run time get object type nameprint(type.name());
Dynamic Type Casting
classAlpha {publicint a;publicint a2;}classBeta:Alpha {publicnewint a;}voidmain() {var b =newBeta();b.a=3; // accesses field Beta.ab.a2=4; // accesses field Alpha.a2 (b asAlpha).a=5; // accesses field Alpha.a Also run time cast}