Guest User

Untitled

a guest
Jan 3rd, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. > makeInverseIndex ["hello world", "world test", "hello test"]
  2. fromList [("hello",fromList [0,2]),("test",fromList [1,2]),("world",fromList [0,1])]
  3.  
  4. > orSearch ["hello", "world"] $ makeInverseIndex ["hello world", "world test", "hello test"]
  5. fromList [0,1,2]
  6.  
  7. > andSearch ["hello", "world"] $ makeInverseIndex ["hello world", "world test", "hello test"]
  8. fromList [0]
  9.  
  10. import Data.List as L
  11. import Data.Map.Strict as M
  12. import Data.Set as S
  13.  
  14. makeInverseIndex :: [String] -> Map String (Set Int)
  15. makeInverseIndex = L.foldr (unionWith S.union . uncurry group) M.empty . zipWithIndex . L.map words
  16. where
  17. zipWithIndex :: [a] -> [(Int, a)]
  18. zipWithIndex xs = zip [0..length xs] xs
  19.  
  20. group :: Ord k => v -> [k] -> Map k (Set v)
  21. group n = M.fromList . L.map (w -> (w, S.singleton n))
  22.  
  23. orSearch :: [String] -> Map String (Set Int) -> Set Int
  24. orSearch words =
  25. M.foldr S.union S.empty . pick words
  26.  
  27. andSearch :: [String] -> Map String (Set Int) -> Set Int
  28. andSearch words =
  29. M.foldr S.intersection (S.fromList [0..length words]) . pick words
  30.  
  31. pick :: Ord k => [k] -> Map k v -> Map k v
  32. pick keys m =
  33. restrictKeys m $ S.fromList keys
Add Comment
Please, Sign In to add comment