Haskell管道过滤不同的值

时间:2016-12-02 08:36:27

标签: haskell filter distinct-values conduit

如果我使用以下Source

 sourceList [1,3,3,1,2,3]

是否可以应用某些过滤器或组合器来仅允许向下游传递不同的值?

所以在我的例子中,只有[1,3,2]会传到下游?

2 个答案:

答案 0 :(得分:5)

这样的事情应该做:

#!/usr/bin/env stack
-- stack --resolver lts-6.19 runghc --package conduit-combinators
import Conduit
import Data.Conduit.List (sourceList)

main = do
    print $ runConduitPure $ sourceList [1,3,3,1,2,3] .| myConduit [] .| sinkList

myConduit dup = do
  num <- await
  case num of
    Just x -> if x `elem` dup
              then myConduit dup
              else do
                yield x
                myConduit (x:dup)
    Nothing -> return ()

执行时:

sibi::casey { ~/scripts }-> ./cond.hs
[1,3,2]

答案 1 :(得分:0)

#!/usr/bin/env stack
-- stack --resolver lts-6.19 runghc --package conduit-combinators
import Conduit
import Data.Conduit.List (sourceList, mapAccum, catMaybes)
import Control.Monad (void)

main = do
    print $ runConduitPure $ sourceList [1,3,3,1,2,3] .| void (mapAccum foo []) .| catMaybes .| sinkList

foo :: Int -> [Int] -> ([Int], Maybe Int)
foo x dup | x `elem` dup = (dup, Nothing)
foo x dup = (x:dup, Just x)

执行时:

C:\Users\Gurkenglas\scripts>stack conduitnub.hs
[1,3,2]