Main Page News Articles Books Fy++ samples Video Files Album Contact Me
Second sample Test

Fy++ code examples

'While' operator

Now while and if can contain a variable declaration inside. This has several advantages: It prevents a programmer from common error: assignment instead of comparison, because of a declaration sequence at the left that assures and clarifies the programmer's intention. It restricts the scope of the variable to the code where it is actually needed, so clarifying its purpose. It is just more simple and short to write and to read.

Example:

while (string s = gets())
{
	print (s);
}

if (string err = get_last_err()) {
	message (s);
	return;
}
// Note that here s and err are undefined.
Is it not simple and beautiful ? :)

'Each' operator

This operator has the following syntax in Fy: each(list;item;index) {} Last two parameters are optional and can be missed. If item is absent then translator defines each variable that can be used inside the loop.

Example:

	string[] wds = {'Alpha', 'Betta', 'Zeta'};
	each (wds) print "\$each\\n";
// Prints each word on a separate line.

'Trap' operator

There is a trap {..} operator in Fy that is used to match, split, grab and replace text strings. It is a very, very powerful thing at all, but now we only talk about two functions - grab() and split(), that you can use with it to search in the text strings. The declaration of them looks like this (the real one is more powerful, but we'll talk about that later):
string[]	split (string, trapid, long count);
string[]	grab (string, trapid, long count);
The string parameter specifies the source text. The trapid is an identifier of a text trap to match against. The count parameter specifies the amount of occurrences to grab or to split into. The functions return null if number of matches is less than requested. Miss it up or set as 0 to match as much as possible. Also note: it can be set to a negative value to start matching from the end of the file; the trap operator always works well to the both directions.

Example:

string file = load_file 'test.txt';
string [] symbols = grab (file, trap { [A-Za-z0-9_]++ });
int ~hash;
each (symbols)
{
	if (hash[each]) hash[each] += 1;
	else hash[each] = 1;
}
	// Show how many times each symbol occurs in the file
message (hash);
If you prefer to talk shortly, then use instead the following code:

Example2:

// This example uses one of the predefined traps symbolic.
// You can define any number of your own traps,
// and then use them in other parts of code.
int ~hash;
each (grab (load_file ('test.txt'), symbolic))
	hash.let (each) ++;
message (hash);
Copyright (c) Sapunov Vladimir 2006-2008 e-mail: vladimir@fyzor.com :: login