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



_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to