Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml error with if statement

Tags:

hash

ocaml

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

like image 477
ppaul74 Avatar asked Dec 17 '22 03:12

ppaul74


1 Answers

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

like image 165
Basile Starynkevitch Avatar answered Feb 10 '23 19:02

Basile Starynkevitch