[Haskell-cafe] [Pipes] Can pipes solve this problem? How?
Mario Blažević
blamario at acanac.net
Thu Aug 16 16:59:00 CEST 2012
On 12-08-15 02:54 PM, Daniel Hlynskyi wrote:
> Hello Cafe.
> Consider code, that takes input from handle until special substring
> matched:
>
> > matchInf a res s | a `isPrefixOf` s = reverse res
> > matchInf a res (c:cs) = matchInf a (c:res) cs
> > hTakeWhileNotFound str hdl = hGetContents hdl >>= return.matchInf str []
>
> So, the question is - can pipes (any package of them) be the Holy
> Grail in this situation, to both keep simple code and better deal with
> handles (do not close them specifically)? How?
It's more complex than Pipes, but SCC gives you what you need. If you
cabal install it, you have the choice of using the shsh executable on
the command line to accomplish your task:
$ shsh -c 'cat input-file.txt | select prefix (>! substring "search
string")'
or using the equivalent library combinators from Haskell code:
> import System.IO (Handle, stdin)
> import Control.Monad.Coroutine (runCoroutine)
> import Control.Concurrent.SCC.Sequential
> pipeline :: String -> Handle -> Producer IO Char ()
> pipeline str hdl = fromHandle hdl >-> select (prefix $ sNot $
substring str)
> hTakeWhileNotFound :: String -> Handle -> IO String
> hTakeWhileNotFound str hdl =
> fmap snd $ runCoroutine $ pipe (produce $ pipeline str hdl)
(consume toList)
> main = hTakeWhileNotFound "up to here" stdin >>= putStrLn
More information about the Haskell-Cafe
mailing list