hashmap

HashList for key:value pairs

In Prolog if you need to use hashes you can use Dicts, but for small number of kv-pairs it is overkill.

In such cases use the HashList that I invented ;). It is very easy and you can use it as a Two way hash too. Very handy.

% HashList utils : [ key1:val1, key2:val2, ... ], also can be used as TwoWaysHash
keys(HL,Res) :- maplist(\I^K^(I = K:_),HL,Res).
vals(HL,Res) :- maplist(\I^V^(I = _:V),HL,Res).
val(Key,HL,Res) :- member(Key:Res,HL).
key(Val,HL,Res) :- member(Res:Val,HL).

-----

?- use_module(library(lambda)).

?- H = [first:john, last:doe, city:huston, state:tx],
keys(H,Keys),vals(H,Vals),
val(city,H,Val),key(huston,H,Key).

H = [first:john, last:doe, city:huston, state:tx],
Keys = [first, last, city, state],
Vals = [john, doe, huston, tx],
Val = huston,
Key = city .

List to Map

Here is and easy way to convert List to a Map where the index is used as key :

import java.util.*;

public class Test {
  
 public static <ARG> void say(ARG arg) { System.out.println(arg); }

 public static HashMap<Integer, ?> list2map(List lst) {
    HashMap map = new HashMap();
	for (int i=0; i < lst.size(); i++) {
		map.put(i, lst.get(i));
	}
	return map;
  }

  public static void main(String[] args) {
      List a = Arrays.asList( 1,2,3,4 );
      say(a);
      say(list2map(a));
  }
}

Output:

[1, 2, 3, 4]
{0=1, 1=2, 2=3, 3=4}

You can directly test it (the code already setup for you) here in OneCompiler editor : https://onecompiler.com/java/3xh55parb