Counting and Filtering Arrow for HXT

I am trying to parse XML, but I want to filter and retrieve only a certain number of children from a given node. For instance:

<root> <node id="a" /> <node id="b" /> <node id="c" /> <node id="d" /> </root> 

And then, if I getChildren >>> myFilter 2 arrow, I will only return nodes with identifiers "a" and "b".

Intuition suggests that I should use the status arrow to track, but I don’t know how to do this.

I tried to do it myself, but this is not quite what I want, it does not look very elegant and does not work. I am trying to start my arrow chain with runSLA and an integer parameter as the initial state, and then determine:

 takeOnly :: IOSLA Int XmlTree XmlTree takeOnly = changeState (\sb -> s-1) >>> accessState (\sb -> if s >= 0 then b else Nothing) 

But of course, I cannot return Nothing , I need to return XmlTree. But I don’t want to return anything at all!

There is probably a better way out. Can you help me?

Thanks for your time and help!

+6
haskell state arrows hxt
source share
1 answer

It would probably be more idiomatic to use combinators in Control.Arrow.ArrowList to handle this.

The package provides (>>.) :: abc -> ([c] -> [d]) -> abd , which is "a combinator for converting the result of a list arrow to another list." This allows us to use the take function that we already have for lists in this context.

Here is a short version of how you can use it:

 module Main where import Text.XML.HXT.Arrow takeOnly :: (ArrowXml a) => Int -> a XmlTree XmlTree takeOnly n = getChildren >>. take n main = do let xml = "<root><node id='a' /><node id='b' />\ \<node id='c' /><node id='d' /></root>" print =<< runX (readString [] xml >>> getChildren >>> takeOnly 2) 

I find that roughly what you are looking for is:

 travis@sidmouth % ./ArrowTake [NTree (XTag (LP node) [NTree (XAttr (LP id)) [NTree (XText "a") []]]) [], NTree (XTag (LP node) [NTree (XAttr (LP id)) [NTree (XText "b") []]]) []] 

No IOSLA . Notice that I also changed the type of the function a bit - this version seems more pleasant to me, but you can easily convert it to something more similar to the type of your version.

+4
source share

All Articles