I have a list of lists, eg [[1;2;3];[2];[3;4;5;6]; [7;8;9;10] I want to place these in a Hashtbl where the key is the length of the list and the value is list of lists, which contains all sublists of the given length.
So for the example above the hash will look like as follows
Key Value
1 [[2]]
3 [[1;2;3]]
4 [[3;4;5;6];[7;8;9;10]]
In addition I am also trying to keep track of the length of the longest list and that number is what is returned by the function
The code that does this is as follows.
let hashify lst =
let hash = Hashtbl.create 123456 in
let rec collector curmax lst =
match lst with
[] -> curmax
| h::t -> let len = (List.length h) in
(if ((Hashtbl.mem hash len)=true)
then ( let v = (Hashtbl.find hash len) in Hashtbl.add hash len v@[h] ) (* Line 660 *)
else ( Hashtbl.add hash len [h]));
(collector (max len curmax) t)
in
collector 0 lst
;;
Now when I do this I get the following error for the code above
File "all_code.ml", line 600, characters 50-72:
Error: This expression has type unit but an expression was expected of type
'a list
Why does Ocaml require a return type of 'a list and how do I fix this. Thanks in advance Puneet
You probably should add parenthesis in (v@[h])
to avoid have it parsed as (Hashtbl.add hash len v)@[h]
And you probably should not pass 123456 to Hashtbl.create
but a reasonable prime number like 307 or 2017
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With