3

我正在使用返回 Maybe 元素的链式函数来过滤列表。这部分工作正常。

{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, OverlappingInstances #-}
import Control.Monad
import Control.Monad.Trans.Maybe
import Control.Monad.Writer
import Data.Map (Map, alter, empty, unionWith)

------------------------------------------------

main = do
  let numberList = [1..6]
  let result = filter ((\z -> case z of Just _ -> True; Nothing -> False) . numFilter) numberList
  (putStrLn . show) result

{-
 [2,3,4]
-}

--- Maybe
bigOne :: Int -> Maybe Int
bigOne n | n > 1     = Just n
         | otherwise = Nothing

lessFive :: Int -> Maybe Int
lessFive n | n < 5     = Just n
           | otherwise = Nothing

numFilter :: Int -> Maybe Int
numFilter num = bigOne num
            >>= lessFive

但是我也想计算不同函数捕获元素的时间。我现在正在使用带有地图的 Writer 来收集点击量。我尝试将其包装在 MaybeT 中,但这会导致整个过滤器在出现不需要的元素并返回和空列表的情况下失败。

-------------------------------
type FunctionName = String
type Count = Int
type CountMap = Map FunctionName Count

instance Monoid CountMap where
  mempty = empty :: CountMap
  -- default mappend on maps overwrites values with same key,
  -- this increments them
  mappend x y = unionWith (+) x y

{-
  Helper monad to track the filter hits.
-}
type CountWriter = Writer CountMap

incrementCount :: String -> CountMap
incrementCount key = alter addOne key empty

addOne :: Maybe Int -> Maybe Int
addOne Nothing = Just 1
addOne (Just n) = Just (n + 1)

bigOneMW :: Int -> MaybeT CountWriter Int
bigOneMW n | n > 1     = MaybeT $ return (Just n)
           | otherwise = do
                          tell (incrementCount "bigOne")
                          MaybeT $ return Nothing

lessFiveMW :: Int -> MaybeT CountWriter Int
lessFiveMW n | n < 5     = MaybeT $ return (Just n)
             | otherwise = do
                           tell (incrementCount "lessFive")
                           MaybeT $ return Nothing

chainMWBool :: Int -> MaybeT CountWriter Bool
chainMWBool n = do
             a <- bigOneMW n
             b <- lessFiveMW a
             return True

chainerMW :: [Int] -> MaybeT CountWriter [Int]
chainerMW ns = do
               result <- filterM chainMWBool ns
               return result
{-
> runWriter (runMaybeT (chainerMW [1..3]))
(Nothing,fromList [("bigOne",1)])
> runWriter (runMaybeT (chainerMW [2..5]))
(Nothing,fromList [("lessFive",1)])
> runWriter (runMaybeT (chainerMW [2..4]))
(Just [2,3,4],fromList [])
-}

我只是不知道如何让它做我想做的事。我猜我正在寻找的类型签名是[Int] -> CountWriter [Int],但是当输入是[1..6]

([2,3,4], fromList[("bigOne", 1), ("lessFive", 2)])
4

2 回答 2

4

当你说:

但是当输入为 [1..6] 时如何得到这样的结果:

([2,3,4], fromList[("bigOne", 1), ("lessFive", 2)])

换句话说,你想要一个将列表作为输入并返回一个列表和一个映射作为输出的东西:

newtype Filter a = Filter { runFilter :: [a] -> (CountMap, [a]) }

为什么不直接使用您实际想要的表示对所有过滤器进行编码:

import Data.List (partition)
import qualified Data.Map as M
import Data.Monoid

newtype CountMap = CountMap (M.Map String Int)

instance Show CountMap where
    show (CountMap m) = show m

instance Monoid CountMap where
    mempty = CountMap M.empty
    mappend (CountMap x) (CountMap y) = CountMap (M.unionWith (+) x y)

filterOn :: String -> (a -> Bool) -> Filter a
filterOn str pred = Filter $ \as ->
    let (pass, fail) = partition pred as
    in  (CountMap (M.singleton str (length fail)), pass)

bigOne :: Filter Int
bigOne = filterOn "bigOne" (> 1)

lessFive :: Filter Int
lessFive = filterOn "lessFive" (< 5)

我们缺少一个难题:如何组合过滤器。好吧,事实证明我们的Filter类型是 a Monoid

instance Monoid (Filter a) where
    mempty = Filter (\as -> (mempty, as))
    mappend (Filter f) (Filter g) = Filter $ \as0 ->
        let (map1, as1) = f as0
            (map2, as2) = g as1
        in  (map1 <> map2, as2)

有经验的读者会认识到这只是State伪装的单子。

(<>)这使得使用(ie )组合过滤器变得很容易mappend,我们只需打开我们的Filter类型即可运行它们:

ghci> runFilter (bigOne <> lessFive) [1..6]
(fromList [("bigOne",1),("lessFive",2)],[2,3,4])

这表明最好的路径是最直接的路径!

于 2013-05-26T18:35:32.680 回答
2

好吧,这里的问题是短路的使用正在破坏您构建的 CountMap。一个简单的例子

test :: MaybeT (Writer [String]) ()
test = do
       tell ["Blah"] >> mzero
       tell ["Blah"] >> mzero
       tell ["Blah"] >> mzero
       tell ["Blah"] >> mzero


Prelude> runWriter (runMaybeT test)
   (Nothing, ["Blah"])

看到问题了吗?

修复它非常简单,只是不要依赖短路:)

例子*:

bigOneMW n | n > 1     = return True
           | otherwise = tell "bigOne" >> return False
lessFiveMW n | n < 5     = return True
             | otherwise = tell "lessFive" >> return False
chainMWBool n = liftM2 (&&) (bigOneMW n) (lessFiveMW n)
chainerMW ns = filterM chainMWBool ns

当然,现在这个MaybeT层有点没有意义,所以我们可以放弃它。

令人高兴的是,这不会影响上述任何代码。

*您会注意到tells 只是使用纯字符串,为此,我使用了语言扩展OverloadedStringsIsStringData.String. 如果你好奇的话,实现这项工作的代码如下所示:

instance IsString CountMap where
  -- This is the same as your incrementOne code
  -- Just a bit more reliant on higher order function and
  -- pointfree.
  fromString = flip (alter inc) empty
    where inc = maybe (Just 1) $ Just . (+1)

你是否喜欢那个特别的技巧取决于你:)

毕竟代码已经完成:http ://hpaste.org/88624

于 2013-05-26T17:51:54.590 回答