Functional-programming-tuple
提供:Dev Guides
関数型プログラミング-タプル
タプルは、固定数の用語を持つ複合データ型です。 タプル内の各用語は、*要素*と呼ばれます。 要素の数は、タプルのサイズです。
C#でタプルを定義するプログラム
次のプログラムは、4つの用語のタプルを定義し、オブジェクト指向プログラミング言語である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でタプルを定義するプログラム
次のプログラムは、4つの用語のタプルを定義し、関数型プログラミング言語であるErlangを使用して印刷する方法を示しています。
-module(helloworld).
-export([start/0]).
start() ->
P = {1,2,3,{4,5}} ,
io:fwrite("~w",[P]).
それは次の出力を生成します-
{1, 2, 3, {4, 5}}
タプルの利点
タプルには次の利点があります-
- タプルは、自然に細かくサイズ設定されています。 タプルに要素を追加したり、タプルから要素を削除することはできません。
- タプル内の任意の要素を検索できます。
- タプルは値のセットが一定であるため、リストよりも高速です。 *タプルは、文字列、数値などの不変の値を含むため、辞書キーとして使用できます。
タプルとリスト
Tuple | List |
---|---|
Tuples are* immutable*, i.e., we can’t update its data. | List are mutable, i.e., we can update its data. |
Elements in a tuple can be different type. | All elements in a list is of same type. |
Tuples are denoted by round parenthesis around the elements. | Lists are denoted by square brackets around the elements. |
タプルの操作
このセクションでは、タプルで実行できるいくつかの操作について説明します。
挿入された値がタプルかどうかを確認します
メソッド* 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