Question

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.

Was it helpful?

Solution

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:

using MyTuple = Tuple<Tuple<Argument, string>, Argument>;
using MyTuple2 = Tuple<Argument, string>;

public class MyClass {

    private MyTuple f(string e, List<Argument> valid) {
        var p = valid.Find( x => { return e.StartsWith( x.value ); } );
        if ( p == null )
           return new MyTuple( null, null );
        if ( p.flag )
           return new MyTuple( new MyTuple2( p, "" ), null );
        if ( p.separator.Equals(" ") && p.value.Length == e.Length )
            return new MyTuple( null, p );
        var si = e.IndexOf(p.separator);
        if ( si != p.value.Length )
            return MyTuple( null, null );
        return new MyTuple( new MyTuple2( p, 
            e.Substring( si + p.separator.Length ) ), null );
    }
}

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:

var s = new List<string> { "one", "two", "three" };

OTHER TIPS

Taking a look at your line that illustrates the "ugliness" of explicitly declaring tuple types:

// ugly code
return new Tuple<Tuple<Argument, String>, Argument>( new Tuple<Argument, String>( p, "" ), null );

1) Idiomatic C# would probably explicitly define a class

class ArgumentMatch {
    public Argument Key;
    public string Value;
    public Argument Unmatched;
}
// if you define the constructor
return new ArgumentMatch(p, "", null);
// or using object initializer syntax,
return new ArgumentMatch { Key = p, Value = "" };

2) You can write your own general utility functions to avoid explicit tuple declaration. C# will infer types on functions, just not on constructors.

// using standard static method
static Tuple<T,U> MakeTuple<T,U>(T a, U b) { return new Tuple<T,U>(a,b); }
// and extension method (I don't personally like this since it's a bit 
// of a name-space pollutant)
static Tuple<T,U> Pair<T,U>(this T a, U b) { return new Tuple<T,U>(a,b); }

return MakeTuple(MakeTuple(p, ""), (Argument)null); 
return p.Pair("").Pair((Argument)null);

3) F# is almost line-for-line translation of the scala example. If you're okay with using scala, you might consider using F# in .NET.

// F# example code
match valid.find(fun x -> e.StartsWith(x.Value)) with
| Some(p) ->
    if p.flag then
        (p, ""),None
    elif p.separator = " " && p.Value.Length = e.Length then
        (None,None),Some(p)
 ....

This question may be old.

However, after 4 years, Microsoft implements ValueTuples in C# 7. So instead of return Tuples<T1,T2>, you can simply return (T1 a, T2 b). More details here https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples

This tuple uses System.ValueTuple which is a struct (value type) instead of System.Tuple which is a class (reference type).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top