Combine Lists with Same Heads in a 2D List (OCaml)

Posted by Atticus on Stack Overflow See other posts from Stack Overflow or by Atticus
Published on 2011-01-17T02:08:04Z Indexed on 2011/01/17 4:53 UTC
Read the original article Hit count: 210

Filed under:

Hi guys, I'm working with a list of lists in OCaml, and I'm trying to write a function that combines all of the lists that share the same head. This is what I have so far, and I make use of the List.hd built-in function, but not surprisingly, I'm getting the failure "hd" error:

let rec combineSameHead list nlist = match list with
 | [] -> []@nlist
 | h::t -> if List.hd h = List.hd (List.hd t)
    then combineSameHead t nlist@uniq(h@(List.hd t))
    else combineSameHead t nlist@h;;

So for example, if I have this list:

[[Sentence; Quiet]; [Sentence; Grunt]; [Sentence; Shout]]

I want to combine it into:

[[Sentence; Quiet; Grunt; Shout]]

The function uniq I wrote just removes all duplicates within a list. Please let me know how I would go about completing this. Thanks in advance!

© Stack Overflow or respective owner

Related posts about ocaml