Commits

Grzegorz Chrupała committed ad91567

Fooling around with Traversable.

Comments (0)

Files changed (1)

nlp-scores/NLP/Scores.hs

     , countJoint
     , countFst
     , countSnd
-    -- * Extracting lists of values from Counts
+    -- * Extracting lists of values from 'Counts'
     , fstElems
     , sndElems
     )
 where
 import qualified Data.Foldable as F
+import qualified Data.Traversable as T
 import Data.Monoid
 import Data.List hiding (sum)
 import qualified Data.Set as Set
 -- | Accuracy: the proportion of elements in the first sequence equal
 -- to elements at corresponding positions in second
 -- sequence. Sequences should be of equal lengths.
-accuracy :: (Eq a, Fractional c, F.Foldable t) =>  t a -> t a -> c
-accuracy xs = mean . map fromEnum . zipWith (==) (F.toList xs) . F.toList
+accuracy :: (Eq a, Fractional c, T.Traversable t) =>  t a -> t a -> c
+accuracy xs = mean . fmap fromEnum . zipWithTF (==) xs . F.toList
 {-# SPECIALIZE accuracy :: [Double] -> [Double] -> Double #-}
 
 -- | Reciprocal rank: the reciprocal of the rank at which the first arguments
 -- | List of values of second element
 sndElems :: Counts a k -> [k]
 sndElems = Map.keys . marginalSnd
+
+-- | @zipWithTF h t f@ zips the values from the traversable @t@ with
+-- the values from the foldable @f@ using the function @h@.
+zipWithTF :: (T.Traversable t, F.Foldable f) =>
+             (a -> b -> c) -> t a -> f b -> t c
+zipWithTF h t f = snd . T.mapAccumL map_one (F.toList f) $ t
+  where map_one (x:xs) y = (xs, h y x)
+