0

I am having a problem with my function, I want to do a pattern matching on a string with my function but I have a problem with breaking the string into substrings. I want for a string like "ccaabbccaacc" and a regular expresion like "a*b*c*" to obtain ["cc", "aabbcc", "aacc", ""], a list with the breaked subtring. I have made this function which returns all the parts of the substring

parts :: [a] -> [[[a]]]
parts [ ] = [[ ]]
parts [c] = [[[c]]]
parts (c : cs) = concat [[(c : p) : ps ,[c] : p : ps] | p : ps <- parts cs]

but when I apply my matchs function overt all the results it returns more that i want and i don't know how to filter the results. Can somene help me?

2
  • 1
    While it is generally a good idea to break such a problem into easy steps like you do here, I think this is an example where it's more effective to write one recursive function that does the job entirely. Have you tried that, yet? Commented Apr 28, 2013 at 13:11
  • I tried to do something recursive but it didn't work Commented Apr 28, 2013 at 13:29

1 Answer 1

1

I take it that this question is about parsing - that you want to break a string up into maximal chunks matching a given regexp, e.g. "a*b*c*".

That's like iterated lexer application, only with regexp. Assuming the existence of function

reglex :: String -> String -> (String, String)

that takes a regexp string, an input string, and returns a pair of longest matching prefix, and the rest of the input string, we can write

import Control.Arrow

parts reg str = ($ ("",str)) $
   iterate (reglex reg . snd) >>>
   tail >>>
   span (not.null.fst) 

and then do something with the result of this.

Sign up to request clarification or add additional context in comments.

2 Comments

Does Haskell have any built-in function for extracting a substring between two specified indices (from one specific string)?
we can do this with repeated application of splitAt: between i j str = let (a,b)=splitAt i str; (c,d)=splitAt (j-i) b in c, zero-based, non-inclusive of j. "simplified" as btw i j s = fst . splitAt (j-i) . snd . splitAt i $ s.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.