元组是具有固定数量项的复合数据类型,元组中的每个术语称为 element 元素。元素的数量是元组的大小。
C#定义元组
以下程序显示了如何定义四个术语的元组并使用C#(一种面向对象的编程语言)打印它们。
using System; public class Test { public static void Main() { var t1 = Tuple.Create(1, 2, 3, new Tuple<int, int>(4, 5)); Console.WriteLine("Tuple:" + t1); } }
它将产生以下输出-
Tuple :(1, 2, 3, (4, 5))
Erlang定义元组
以下程序显示了如何定义四个术语的元组并使用函数编程语言Erlang打印它们。
-module(helloworld). -export([start/0]).start() -> P = {1,2,3,{4,5}} ,
io:fwrite("~w",[P]).
它将产生以下输出-
{1, 2, 3, {4, 5}}
元组操作
在本节中,我们将讨论可以在元组上执行的一些操作。
检查插入的值是否为元组
方法 is_tuple(tuplevalues)用于确定插入的值是否为元组。当插入的值是元组时,它返回 true ,否则返回 false 。例如,
-module(helloworld). -export([start/0]).start() ->
K = {abc,50,pqr,60,{xyz,75}} , io:fwrite("~w",[is_tuple(K)]).
它将产生以下输出-
True
将列表转换为元组
方法 list_to_tuple(listvalues)将列表转换为元组。例如,
-module(helloworld). -export([start/0]).start() ->
io:fwrite("~w",[list_to_tuple([1,2,3,4,5])]).
它将产生以下输出-
{1, 2, 3, 4, 5}
将元组转换为列表
方法 tuple_to_list(tuplevalues)将指定的元组转换为列表格式。例如,
-module(helloworld). -export([start/0]).start() ->
io:fwrite("~w",[tuple_to_list({1,2,3,4,5})]).
它将产生以下输出-
[1, 2, 3, 4, 5]
检查元组大小
方法 tuple_size(tuplename)返回一个元组的大小。例如,
-module(helloworld). -export([start/0]).start() ->
K = {abc,50,pqr,60,{xyz,75}} ,
io:fwrite("~w",[tuple_size(K)]).
它将产生以下输出-
5