Logo

Programming-Idioms

  • Go
  • C++
  • Fortran
  • Python
  • Java

Idiom #220 Create a tuple value

Create t consisting of 3 values having different types.

Explain if the elements of t are strongly typed or not.

record Tuple(int a, String b, boolean c) {}
var t = new Tuple(1, "hello", true);

Strongly typed.
record is available since Java 16
record Tuple<A, B, C>(A a, B b, C c) {}
Tuple<String, Integer, Boolean> t
    = new Tuple<>("abc", 123, true);
class Tuple {
    String s;
    int i;
    boolean b;
}
record Tuple(Object ... a) {}
Tuple t = new Tuple("abc", 123, true);
t := []any{
	2.5,
	"hello",
	make(chan int),
}

A slice of empty interface may hold any values (not strongly typed).
a, b, c := 2.5, "hello", make(chan int)

a, b, c are strongly typed and could hold the multiple return values of a func.

While a, b, c can most often be used like a tuple, they are technically not a tuple named t.
#include <tuple>
std::tuple<float, std::string, bool> t(2.5f, "foo", false);

Strongly typed, can include any primitive or class and be of arbitrary (but fixed) length.
#include <tuple>
auto t = std::make_tuple(2.5f, std::string("foo"), false);

Types are inferred.
t = (2.5, "hello", -1)

Tuples are immutable.
They may be created with elements of any type.
t = tuple('abc', 123, true)
let t = 1, 'a', "b"

in OCaml, parenthesis for tuples are optional and only used to disambiguate.
Type inference can determine the type of the tuple without annotation.

New implementation...
programming-idioms.org