tags:

views:

55

answers:

2

I would like to take a string representation of a set and parse it. Does anybody know of any pre-existing libraries?

I can write the regular expression to match these patterns, but it doesn't seem to me to be a very efficient method of doing things. Also some edge cases will allow certain strings to pass which shouldn't, and I'm probably missing some other cases.

For example, I would like to parse strings like the following:


"{10,-20,30.5,-40.01,.5,-.5}" 
//^\{((-?[0-9]*(\.[0-9]+)?)(?:,|\}))+$
 .Parse()
 .ShouldEqual(new [] { 10,-20,30.5,-40.01,.5,-.5 });

"{(10,10),(20,2),(30.2,-5.5),(-5,40),(-.2,3000),(-.1,-.2)}" 
//^\{(\((-?[0-9]*(\.[0-9]+)?),(-?[0-9]*(\.[0-9]+)?)\)(?:,|}))+$
 .Parse()
 .ShouldEqual(new [] {
   new Point(10,10),
   new Point(20,2),
   new Point(30.2,-5.5),
   new Point(-5,40),
   new Point(-.2,3000),
   new Point(-.1,-.2)
 });

"{(10,[10,1]),(20,[2,4]),(30.2,[-5.5,-10]),(-5,[40,10]),(-.2,[3000,10]),(-.1,[-.2,0])}"
//^\{(\((-?[0-9]*(\.[0-9]+)?),\[((-?[0-9]*(\.[0-9]+)?)(?:,|\]))+\)(?:,|}))+$
 .Parse()
 .ShouldEqual(new [] {
   new Point(10,new[]{ 10,1 }),
   new Point(20,new[]{2,4}),
   new Point(30.2,new[]{-5.5,-10}),
   new Point(-5,new[]{40,10}),
   new Point(-.2,new[]{3000,10}),
   new Point(-.1,new[]{-.2,0})
 });

The Point class is arbitrary.

A: 

Embedding IronPython and using the Execute method might be a good option.

Here's a StackOverflow question on the topic.

Also see A 3 minute guide to embedding IronPython in a C# application

Dennis Palmer
I'm not familiar with Python, I'm guessing syntax comparable? I know it would translate directly in javascript. :)
Dave
+1  A: 

I don't know a .net-library that could do so.

How complex should the set representations be? Does it just consist of

  • tuples
  • values
  • subsets

or should this also allow complex constructs like intervals or set comprehensions? ({ f(x) | x <- [1, 10), g(x) < 42 ^ q(x) = 0 }).

If your set just has a simple form (maybe just an enumeration of values), I would parse it manually using regular expressions or builtin String-functions.

Otherwise this should be quite hard to parse and evaluate - Consider using a compiler-compiler-tool like Irony

Note that sets are unordered and can also be infinite. Your array-based output doesn't fit well here - You'll first have to develop a concept of representing sets. Or do you just want to parse a list?

Dario
That's where I was headed, just wanted to make doubly sure i wasn't recreating the wheel. Was just in the midst of writing my tests and it just seems like something that there might be a library for.
Dave