Up

SYSPACK - Object Dictionnary

Create, delete, save, update a string/objects associative array, similar to a Python dictionary, a Java hashMap or a Perl hash.

You can add different object types in a same dictionnary, there is no problem for that. However, i don't recommend this usage. Indeed, the function DictList can become unstable because a list can not have several types. With the functions DictGet and DictGetNth, be careful when you perform these in a reflexive Scol function (see the second example below).

Thus, i recommend to use the same object type in a dictionnary. Otherwise, be really careful at that you do

By alphabetic order

See also

String dictionnary

Example

typeof dict = Dict;;
struct CLIENT = [
	name : S,
	city : S,
	age : I
	] mkCLIENT;;
typeof clis = [CLIENT r1];;

fun clisCr ()=
	(mkCLIENT ["Ines" "Barcelona" 31]) ::
	(mkCLIENT ["Tina" "Napoli" 24]) ::
	(mkCLIENT ["Uma" "Los Angeles" 42]) ::
	nil;;		
	
fun ditctAddClis (list, n)=
	if list == nil then
		0
	else
	(
		if 0 == DictAdd dict strcat "client " itoa n hd list then
			ditctAddClis tl list n+1
		else
			1
	);;

fun displayList (list)=
	if list == nil then
		""
	else
		let hd list -> [key cli] in
		sprintf "%s : %s %s %d\n%s" [key cli.name cli.city cli.age displayList tl list];;
		
fun main ()=
	_showconsole;
	
	set dict = DictNew _channel;
	set clis = clisCr;
	_fooId ditctAddClis clis 0;		// 0
	
	let DictGet dict "client 2" nil -> cli in
	_fooS sprintf "%s %s %d" [cli.name cli.city cli.age];	// Uma Los Angeles 42
	
	_fooId DictFind  dict "client 1";		// 1
	_fooId DictFind  dict "client 5";		// 0
	
	_fooS displayList DictList dict nil;
	/* client 0 : Ines Barcelona 31
	client 2 : Uma Los Angeles 42
	client 1 : Tina Napoli 41 */
	
	let 0 -> i in
	while (i < DictCount dict) do
	(
		let DictGetNth dict i nil -> cli in
		_fooS sprintf "%d -> %s %s %d" [i cli.name cli.city cli.age];
		set i = i + 1;
	);
	/* 0 -> Ines Barcelona 31
	1 -> Tina Napoli 24
	2 -> Uma Los Angeles 42 */
	
	_fooId DictAdd dict "Bob" ["Alice" 1];		// 0
	printf "Bob = %s : %d" DictGet dict "Bob" nil 0;		// Bob = Alice : 1
	printf "Bob = %s : %d" DictGetNth dict 3 nil 0;		// Bob = Alice : 1
	
	_fooId DictCount dict;		// 4
	
	_fooId DictDestroy dict;		// 0
	0;;

Other example to show a dangerous way :

typeof dict = Dict;;

fun reflexiveFunction (list)
	if list == nil then
		0
	else
		let hd list -> [key value] in
		(
		_fooS value;	// incorrect !!! the first element is a S, the second is an I
		reflexiveFunction tl list
		);;

fun main ()=
	_showconsole;
	
	set dict = DictNew _channel;
	DictAdd dict "Scol";	// value is a string (S)
	DictAdd dict 1;			// value is an integer (I)
	reflexiveFunction DictList dict nil;
	_fooS DictGetNth dict 0 nil;		// correct, value is a S
	_fooId DictGetNth dict dict 1 nil;	// correct, value is a I
	0;;