folding - let sorted = List.stable_sort(fun(k1(k2>...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
let max2 (lst : int list) : int = match lst with ([] | [_])-> failwith "length of list < 2" | x1::x2::xs -> let _, max2 = List.fold_left (fun (max1, max2) x -> if x > max1 then (x, max1) else if x > max2 then (max1, x) else (max1, max2)) (max x1 x2, min x1 x2) xs in max2 let powerset (lst : 'a list) : ('a list list) = List.fold_left (fun sets x -> sets @ (List.map (fun s -> x::s) sets)) [[]] lst (* Runs in O(nlog(n)) time *) let inverted_index (pages : string list list) : (string * int list) list = let collect (kv_pairs : (string * int) list) : (string * (int list)) list =
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: let sorted = List.stable_sort (fun (k1, _) (k2, _) -> String.compare k1 k2) kv_pairs in List.fold_left (fun collected (k, v) -> match collected with -> [(k,[v])] | (_, )::_ -> failwith "impossible" | (k', v'::vs)::xs -> if k = k' && v != v' then (k, v::v'::vs)::xs else if k <> k' then (k,[v])::collected else collected) sorted in let index, _ = List.fold_left (fun (words, page_num) page -> let words' = (List.map (fun word -> (word, page_num)) page) @ words in (words', 1+page_num)) (, 0) pages in List.rev (collect index)...
View Full Document

Ask a homework question - tutors are online