let stable_unique xs =
  let seen = Hashtbl.create 8 in
  let result = ref [] in
  List.iter (fun x ->
    if not (Hashtbl.mem seen x) then begin
      Hashtbl.add seen x ();
      result := x :: !result
    end
  ) xs;
  List.rev !result

;;

List.length (stable_unique [3;1;4;1;5;9;2;6;5;3;5;8;9])
+ List.fold_left (+) 0 (stable_unique [3;1;4;1;5;9;2;6;5;3;5;8;9])
