I have written a program or algorithm that parses command line arguments. First, one needs to specify valid arguments and their attributes (flag, separator and so on).
Now, I have a helper function that returns: Tuple<Tuple<Argument, String>, String>: the first element in the Tuple (which is a tuple too) contains a “key-value-pair”, null if no pair could be found. The second element contains a string that was identified as an option and separator was " " (meaning the value will be the next element in the command line)
The code for that function is as follows:
private Tuple<Tuple<Argument, String>, Argument> f(string e, List<Argument> valid) {
var p = valid.Find( x => { return e.StartsWith( x.value ); } );
if ( p == null )
return new Tuple<Tuple<Argument, String>, Argument>( null, null );
if ( p.flag )
return new Tuple<Tuple<Argument, String>, Argument>( new Tuple<Argument, String>( p, "" ), null );
if ( p.separator.Equals(" ") && p.value.Length == e.Length )
return new Tuple<Tuple<Argument, String>, Argument>( null, p );
var si = e.IndexOf(p.separator);
if ( si != p.value.Length )
return new Tuple<Tuple<Argument, String>, Argument>( null, null );
return new Tuple<Tuple<Argument, String>, Argument>( new Tuple<Argument, String>( p, e.Substring( si + p.separator.Length ) ), null );
}
Is there any way to write this shorter? Do I have to explicitly put the Generics there?
Obviously, creating own classes for that would be a solution. But isn’t there another?
For reference, the same code in Scala looks like this:
val po = valid.find(p => e.startsWith(p.value))
po match {
case Some(p) =>
if ( p.flag )
(Some((p, "")), None)
else if ( p.separator.matches(" |\t") && p.value.length == e.length )
(None, Some(p))
else {
val si = e.indexOf(p.separator)
if ( si != p.value.length )
(None, None)
else
(Some((p, e.substring(si + p.separator.length))), None)
}
case _ => (None, None)
}
Plus, is there a way to initiate Lists or Tuples in a compact way? As in List(1, 2, 3, 4) or (Key, Value) instead of Tuple<KeyType, ValueType>(Key, Value)
Regards,
Danyel.
You can use typedefs to clean up the code. Technically, C# doesn’t have typedefs, but you can use usings to simulate them. Something like this:
Regarding your question about initialization, I’m not sure i understand. Tuples already have a compact initialization method, using constructor arguments.
Lists can use initializers, like this: