Loading ...
Sorry, an error occurred while loading the content.

13943how to simplify "nesting" of lists when using fold

Expand Messages
  • Jean Saint-Remy
    Aug 23, 2013
    • 0 Attachment
      Hi,

      I am trying to reduce complexity when "collating" lists of lists. The auto parts database program seems to work for the time being, but the share holders are not amused when we try to run inventory reports.

      let (db : (int, 'a list ref) Hashtbl.t) = Hashtbl.create 10 ;;
      exception Invalid_entry of string;;
      let add tbl key data =

        let more =

        if (Hashtbl.mem tbl key) then raise (Invalid entry "Item already in database")
        else
          let more = ref [] in
          Hashtbl.add tbl key more;
          more in
          more := data :: [] ;;
      add db 10100321 ["10100321"; "transverse axle and bearing"; "third shelf; 2 isle; upper lory"; "vendor part number 33001"; "y"; "199.99";] ;;
      add db 10100322 ["10100322"; "gear box"; "2nd shelf, 5th isle, upper lory"; "vendor part number 45002"; "y"; "139.99"; ] ;;
      add db 10100416 ["10100416"; "spring release"; "1st shelf;2nd isle; lower case"; "vendor part number 63102"; "y"; "19.89"; ] ;;

      (* print keys already in database *)
      let keys tbl =

        let key = Hashtbl.fold (fun key value ls -> key :: ls) tbl [] in
        List.fold_left (fun ls x -> if List.mem x ls then ls else x :: ls) [] key ;;

      (* now show inventory *)
      let values tbl =
        let value = Hashtbl.fold (fun key value ls -> value :: ls) tbl [] in

        List.fold_left (fun ls x -> if List.mem x ls then ls else x :: ls) [] value ;;
      # keys db ;;
      -: int list = [10100416; 10100322; 10100321]


      # values db ;;
      - : string list list ref list =
      [{contents =
         [["10100321"; "transverse axle and bearing"; "third shelf; 2 isle; upper lory"; "vendor part number 33001"; "y"; "199.99";]]};
       {contents =
         [["10100322"; "gear box"; "2nd shelf, 5th isle, upper lory"; "vendor part number 45002"; "y"; "139.99"; ]]};
       {contents =
         [["10100416"; "spring release"; "1st shelf;2nd isle; lower case"; "vendor part number 63102"; "y"; "19.89"; ]]}]


      It is fine for generating keys from the hash table, but clearly above we have list inside of a list of a list, which seems to increase the program complexity. We wanted to cons a list of lists [ [list1]; [list2]; [list3] ], but things did not go so well.


      How can we traverse the hash and produce a simple list?  Do we need to call "List.hd" on the result to sort of decompose the lists?

      With kind regards,

      Jean


      [Non-text portions of this message have been removed]
    • Show all 2 messages in this topic