16

I was wondering if there are any languages that allow for named tuples. Ie: an object with multiple variables of different type and configurable name.

E.g.:

public NamedTuple<double:Speed, int:Distance> CalculateStuff(int arg1, int arg2)

var result = CalculateStuffTuple(1,2);

Console.WriteLine("Speed is: " + result.Speed.ToString())
Console.WriteLine("Distance is: " + result.Distance.ToString())

I could conceive how a dynamic could support such a feature. The static languages I usually swim in (like c#) can do a Dictionary, but that's not type safe unless all items are of the same type. Or you can use a Tuple type, but that means you have fixed names of the members (Var1, Var2, etc).

You could also write a small custom class, but that's the situation I'd like to avoid.

I could imagine a macro processing language could script something like that up for you in a static language, but I don't know of such a language.

This comes out of my answer from this question about return types.

2
  • The reason I'd like to avoid a custom class / struct is that I don't like typing! Nothing more than that.
    – ligos
    Sep 30, 2009 at 3:06
  • This line should I thing not include Tuple. var result = CalculateStuffTuple(1,2); Feb 3, 2012 at 11:49

12 Answers 12

40

Old question, but in need of a better solution I think.

You can get named parameters by taking advantage of the Tuple type, but wrapping it in a custom named type that wraps .Item1, .Item2, etc. in meaningful property names.

I too hate the fact that Tuples have unnamed parameters that make code unreadable, but can't ignore the time it saves having to implement IComparable, IStructuralEquatable, etc on your own so that you can safely use your structs as a dictionary key, for instance.

I think this is a very pleasant compromise:

public class Velocity : Tuple<double, double, string>
{
    public Velocity(double Speed, double Direction, string Units) : base(Speed, Direction, Units) { }
    public double Speed { get { return this.Item1; } }
    public double Direction { get { return this.Item2; } }
    public string Units { get { return this.Item3; } }
}

Now instead of this garbage:

Tuple<double, double, string> myVelocity = new Tuple<double, double, string>(10, 2.34, "cm/s");
System.Diagnostics.Debug.Print("Speed: " + myVelocity.Item1);
System.Diagnostics.Debug.Print("Direction: " + myVelocity.Item2);
System.Diagnostics.Debug.Print("Units: " + myVelocity.Item3);

You get to do this:

Velocity myVelocity2 = new Velocity(10, 2.34, "cm/s");
System.Diagnostics.Debug.Print("Speed: " + myVelocity2.Speed);
System.Diagnostics.Debug.Print("Direction: " + myVelocity2.Direction);
System.Diagnostics.Debug.Print("Units: " + myVelocity2.Units);

And you still benefit from all the wonderful tuple features that let you use it as a complex key in dictionaries, etc.

The only downside is that if you only planned on using this tuple within the scope of a single method, you have to declare a type within the scope of that method's containing class. For most applications, I don't think that's a problem.

3
  • That's actually not too bad. Except I have to have a bunch of little classes wrapping around Tuple<>. But its better than having to re-implement IEquatable, IComparable, etc.
    – ligos
    Aug 8, 2012 at 23:47
  • 1
    I can't believe I never thought of this. Super useful. Mar 24, 2014 at 22:45
  • Just the solution I was looking for. Great :) Mar 4, 2015 at 11:02
18

In C#, you have anonymous types; these are similar but have their own limitations:

var result = new { Speed = 12.4, Distance = 8, Caption = "car 1" };

However, it is hard to consume these as a caller, unless you use "cast by example" (brittle), reflection, or dynamic. Of the three, the last is the most appetising.

dynamic result = GetSomething();
Console.WriteLine(result.Speed);
Console.WriteLine(result.Distance);

In most cases, it would be a better idea just to use a regular class - but this approach does have some practical uses; for example, look at how they are used in ASP.NET MVC to pass around configuration information simply and conveniently (which would otherwise require a dictionary). A bit like how jQuery allows you to pass options as properties on an object.

1
  • This appears to be the closest to what I was asking for (at least in c#).
    – ligos
    Sep 30, 2009 at 3:03
7

This is now supported starting from C# 7

(double speed, int distance) CalculateStuff(int arg1, int arg2)

var result = CalculateStuff(1,2);

Console.WriteLine("Speed is: " + result.speed.ToString())
Console.WriteLine("Distance is: " + result.distance.ToString())

See : https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/

6

Eiffel allows named tuples.

5

I know of;

  • Python (dynamic, strong typing)
  • Eiffel (static, string typing)

Both can be used in .net

And probably Lisp, you can do anything with Lisp.

3

You mean, something like Python's collections.namedtuple? Well, Python (the current versions, 2.6 and 3.1) supports them;-). But seriously, I don't know of a statically typed language having them as a built-in.

3

I'm not sure if this is exactly what you're looking for, but in Haskell, you can have a record with specified names and types:

data Movement = Movement { speed :: Double, distance :: Int } deriving (Show)

main = do
    print $ Movement 3.14 100
    print Movement {distance = 5, speed = 2.1}
    print Movement {speed = 9, distance = -4}

output:

Movement {speed = 3.14, distance = 100}
Movement {speed = 2.1, distance = 5}
Movement {speed = 9.0, distance = -4}

But it's technically not a tuple. Haskell does have tuples, but they aren't name-able as far as I know.

This really isn't far from a simple struct in any C-derived language, either. Maybe I missed something in the question.

2

Whats wrong with using structs or classes in C#?

public class SpeedDistance{
  public double Speed;
  public int Distance;
}
3
  • 2
    Well, the public field is a bad idea, of course... but public double Speed {get;set;} would do ;-p Sep 29, 2009 at 4:30
  • 1
    I like my tuples to be immutable. And that requires readonly variables instead and a constructor, which just starts getting too long.
    – ligos
    Sep 30, 2009 at 3:05
  • 1
    public fields are ok, if and only if that is all the class contains. But tuples can also have lots of other nice properties, that help when passing to other libraries. If they are written from scratch each time then they don't interoperate. Feb 3, 2012 at 12:05
2

Several such languages exist. The word for such a named tuple is "record". The ML language family has such records, together with the corresponding types. Concrete languages include: SML, OCaml, and, importantly, F#. This link explains about records in F#: http://en.wikibooks.org/wiki/F_Sharp_Programming/Tuples_and_Records#Defining_Records

1

Swift allows named tuples. You can write something like:

let interval = (start: 0, end: 10)
let start = interval.start

They are in effect anonymous structures.

0

Thank you Alain. Here's how I used your tip.

Dynamic image loader for a carousel

<div id="owl" class="owl-carousel owl-theme">
    @foreach (var image in Model.Sketches)
    {
        <div class="item" >
            <a href="@image.SketchHref" id="[email protected]" target="_blank" >
                <img id="[email protected]" class="lazyOwl" style="border:1px solid #d1c7c7;outline : 0;max-height:350px;max-width:400px;" 
                    title="click for full size" alt="@image.SketchName" data-src="@image.SketchHref" /></a>
                    <div style="text-align:left;height:auto;vertical-align:bottom;padding:2px;font-size:1em;color:#DF3A01;">Sketch @image.SketchNumber of @Model.Sketches.Count()</div>
        </div>
    }
    </div>

And for the C#

    public List<Sketches> Sketches 
    {
        get
        {
            List<Sketches> hrefs = new List<Sketches>();

/* image name matches a folder location example: 1234101005_001.Gif would equal "c:\images\1234\10\1005_BLD\" */

            var sketchFolder = Regex.Replace(some_image, @"(\d{4})(\d{2})(\d{4})", @"c:\Sketches\$1\$2\$3\_BLD");
            var sketchHref = Regex.Replace(some_image, @"(\d{4})(\d{2})(\d{4})", @"/sketches/$1/$2/$3/_BLD");
            Int16 i = 0;

            if (System.IO.Directory.Exists(sketchFolder))
            {
                List<string> gifs = GetGifs(sketchFolder);

                gifs.ForEach(delegate(String gif)
                {
                    string s = sketchHref + "/" + gif;
                    string f = sketchFolder + "/" + gif;

                    if (System.IO.File.Exists(f))
                    {
                        Sketches sketch = new Sketches(s, (++i).ToString(), gif);
                        hrefs.Add(sketch);
                    }
                    else // gif does not exist
                    {
                        Sketches sketch = new Sketches("placeholder.png", (++i).ToString(), gif);
                        hrefs.Add(sketch);
                    }
                });
            }
            else // folder does not exist
            {
                Sketches sketch = new Sketches("placeholder.png", (++i).ToString(), "");
                hrefs.Add(sketch);
            }
            return hrefs;
        }
    }

public class Sketches : Tuple<string, string, string>
{
    public Sketches(string SketchHref, string SketchNumber, string SketchName) : base(SketchHref, SketchNumber, SketchName) { }
    public string SketchHref { get { return this.Item1; } }
    public string SketchNumber { get { return this.Item2; } }
    public string SketchName { get { return this.Item3; } }
}
-1

I am not sure what you would need this for - a tuple is simply a structure that holds different types of data. If you really want named properties you will have to create a custom type or create an anonymous type on the fly.

I am not aware of any statically typed language that would support this either but C# certainly doesn't.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.