Fsharp-arrays

提供:Dev Guides
移動先:案内検索

F#-配列

配列は、すべて同じ型である連続したデータ要素の固定サイズのゼロベースの可変コレクションです。

配列の作成

さまざまな構文と方法を使用して、またはArrayモジュールの関数を使用して、配列を作成できます。 このセクションでは、モジュール関数を使用せずに配列を作成する方法について説明します。

関数なしで配列を作成する3つの構文的な方法があります-

  • [|および|]セミコロンで区切られます。
  • 各要素を個別の行に配置します。この場合、セミコロンセパレータはオプションです。 *シーケンス式を使用する。

ドット演算子(。)と角かっこ([および])を使用して、配列要素にアクセスできます。

次の例は、配列の作成を示しています-

//using semicolon separator
let array1 = [| 1; 2; 3; 4; 5; 6 |]
for i in 0 .. array1.Length - 1 do
   printf "%d " array1.[i]
printfn" "

//without semicolon separator
let array2 =
   [|
      1
      2
      3
      4
      5
   |]
for i in 0 .. array2.Length - 1 do
   printf "%d " array2.[i]
printfn" "

//using sequence
let array3 = [| for i in 1 .. 10 -> i* i |]
for i in 0 .. array3.Length - 1 do
   printf "%d " array3.[i]
printfn" "

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

1 2 3 4 5 6
1 2 3 4 5
1 4 9 16 25 36 49 64 81 100

配列の基本操作

ライブラリモジュールMicrosoft.FSharp.Collections.Arrayは、1次元配列の操作をサポートしています。

次の表は、配列の基本的な操作を示しています-

Value Description
append : 'T [] → 'T [] → 'T [] Creates an array that contains the elements of one array followed by the elements of another array.
average : ^T [] → ^T Returns the average of the elements in an array.
averageBy : ('T → ^U) → 'T [] → ^U Returns the average of the elements generated by applying a function to each element of an array.
blit : 'T [] → int → 'T [] → int → int → unit Reads a range of elements from one array and writes them into another.
choose : ('T → U option) → 'T [] → 'U [] Applies a supplied function to each element of an array. Returns an array that contains the results x for each element for which the function returns Some(x).
collect : ('T → 'U []) → T [] → 'U [] Applies the supplied function to each element of an array, concatenates the results, and returns the combined array.
concat : seq<'T []> → 'T [] Creates an array that contains the elements of each of the supplied sequence of arrays.
copy : 'T → 'T [] Creates an array that contains the elements of the supplied array.
create : int → 'T → 'T [] Creates an array whose elements are all initially the supplied value.
empty : 'T [] Returns an empty array of the given type.
exists : ('T → bool) → 'T [] → bool Tests whether any element of an array satisfies the supplied predicate.
exists2 : ('T1 → 'T2 → bool) → 'T1 [] → 'T2 [] → bool Tests whether any pair of corresponding elements of two arrays satisfy the supplied condition.
fill : 'T [] → int → int → 'T → unit Fills a range of elements of an array with the supplied value.
filter : ('T → bool) → 'T [] → 'T [] Returns a collection that contains only the elements of the supplied array for which the supplied condition returns true.
find : ('T → bool) → 'T [] → 'T Returns the first element for which the supplied function returns true. Raises KeyNotFoundException if no such element exists.
findIndex : ('T → bool) → 'T [] → int Returns the index of the first element in an array that satisfies the supplied condition. Raises KeyNotFoundException if none of the elements satisfy the condition.
fold : ('State → 'T → 'State) → 'State → 'T [] → 'State Applies a function to each element of an array, threading an accumulator argument through the computation. If the input function is f and the array elements are i0…​iN, this function computes f (…​(f s i0)…​) iN.
fold2 : ('State → 'T1 → 'T2 → 'State) → 'State → 'T1 [] → 'T2 [] → 'State Applies a function to pairs of elements from two supplied arrays, left-to-right, threading an accumulator argument through the computation. The two input arrays must have the same lengths; otherwise, ArgumentException is raised.
foldBack : ('T → 'State → 'State) → 'T [] → 'State → 'State Applies a function to each element of an array, threading an accumulator argument through the computation. If the input function is f and the array elements are i0…​iN, this function computes f i0 (…​(f iN s)).
foldBack2 : ('T1 → 'T2 → 'State → 'State) → 'T1 [] → 'T2 [] → 'State → 'State Applies a function to pairs of elements from two supplied arrays, right-to-left, threading an accumulator argument through the computation. The two input arrays must have the same lengths; otherwise, ArgumentException is raised.
forall : ('T → bool) → 'T [] → bool Tests whether all elements of an array satisfy the supplied condition.
forall2 : ('T1 → 'T2 → bool) → 'T1 [] → 'T2 [] → bool Tests whether all corresponding elements of two supplied arrays satisfy a supplied condition.
get : 'T [] → int → 'T Gets an element from an array.
init : int → (int → 'T) → 'T [] Uses a supplied function to create an array of the supplied dimension.
isEmpty : 'T [] → bool Tests whether an array has any elements.
iter : ('T → unit) → 'T [] → unit Applies the supplied function to each element of an array.
iter2 : ('T1 → 'T2 → unit) → 'T1 [] → 'T2 [] → unit) Applies the supplied function to a pair of elements from matching indexes in two arrays. The two arrays must have the same lengths; otherwise, ArgumentException is raised.
iteri : (int → 'T → unit) → 'T [] → unit Applies the supplied function to each element of an array. The integer passed to the function indicates the index of the element.
iteri2 : (int → 'T1 → 'T2 → unit) → 'T1 [] → 'T2 [] → unit Applies the supplied function to a pair of elements from matching indexes in two arrays, also passing the index of the elements. The two arrays must have the same lengths; otherwise, an ArgumentException is raised.
length : 'T [] → int Returns the length of an array. The Length property does the same thing.
map : ('T → 'U) → 'T [] → 'U [] Creates an array whose elements are the results of applying the supplied function to each of the elements of a supplied array.
map2 : ('T1 → 'T2 → 'U) → 'T1 [] → 'T2 [] → 'U [] Creates an array whose elements are the results of applying the supplied function to the corresponding elements of two supplied arrays. The two input arrays must have the same lengths; otherwise, ArgumentException is raised.
mapi : (int → 'T → 'U) → 'T [] → 'U [] Creates an array whose elements are the results of applying the supplied function to each of the elements of a supplied array. An integer index passed to the function indicates the index of the element being transformed.
mapi2 : (int → 'T1 → 'T2 → 'U) → 'T1 [] → 'T2 [] → 'U [] Creates an array whose elements are the results of applying the supplied function to the corresponding elements of the two collections pairwise, also passing the index of the elements. The two input arrays must have the same lengths; otherwise, ArgumentException is raised.
max : 'T [] → 'T Returns the largest of all elements of an array. Operators.max is used to compare the elements.
maxBy : ('T → 'U) → 'T [] → 'T Returns the largest of all elements of an array, compared via Operators.max on the function result.
min : ('T [] → 'T Returns the smallest of all elements of an array. Operators.min is used to compare the elements.
minBy : ('T → 'U) → 'T [] → 'T Returns the smallest of all elements of an array. Operators.min is used to compare the elements.
ofList : 'T list → 'T [] Creates an array from the supplied list.
ofSeq : seq<'T> → 'T [] Creates an array from the supplied enumerable object.
partition : ('T → bool) → 'T [] → 'T [] *'T [] Splits an array into two arrays, one containing the elements for which the supplied condition returns* true, and the other containing those for which it returns false*.
permute : (int → int) → 'T [] → 'T [] Permutes the elements of an array according to the specified permutation.
pick : ('T → 'U option) → 'T [] → 'U Applies the supplied function to successive elements of a supplied array, returning the first result where the function returns Some(x) for some x. If the function never returns Some(x), KeyNotFoundException is raised.
reduce : ('T → 'T → 'T) → 'T [] → 'T Applies a function to each element of an array, threading an accumulator argument through the computation. If the input function is f and the array elements are i0…​iN, this function computes f (…​(f i0 i1)…​) iN. If the array has size zero, ArgumentException is raised.
reduceBack : ('T → 'T → 'T) → 'T [] → 'T Applies a function to each element of an array, threading an accumulator argument through the computation. If the input function is f and the elements are i0…​iN, this function computes f i0 (…​(f iN-1 iN)). If the array has size zero, ArgumentException is raised.
rev : 'T [] → 'T [] Reverses the order of the elements in a supplied array.
scan : ('State → 'T → 'State) → 'State → 'T [] → 'State []) Behaves like fold, but returns the intermediate results together with the final results.
scanBack : ('T → 'State → 'State) → 'T [] → 'State → 'State [] Behaves like foldBack, but returns the intermediary results together with the final results.
set : 'T [] → int → 'T → unit Sets an element of an array.
sort : 'T[] → 'T [] Sorts the elements of an array and returns a new array. Operators.compare is used to compare the elements.
sortBy : ('T → 'Key) → 'T [] → 'T [] Sorts the elements of an array by using the supplied function to transform the elements to the type on which the sort operation is based, and returns a new array. Operators.compare is used to compare the elements.
sortInPlace : 'T [] → unit Sorts the elements of an array by changing the array in place, using the supplied comparison function. Operators.compare is used to compare the elements.
sortInPlaceBy : ('T → 'Key) → 'T [] → unit Sorts the elements of an array by changing the array in place, using the supplied projection for the keys. Operators.compare is used to compare the elements.
sortInPlaceWith : ('T → 'T → int) → 'T [] → unit Sorts the elements of an array by using the supplied comparison function to change the array in place.
sortWith : ('T → 'T → int) → 'T [] → 'T [] Sorts the elements of an array by using the supplied comparison function, and returns a new array.
sub : 'T [] → int → int → 'T [] Creates an array that contains the supplied subrange, which is specified by starting index and length.
sum : 'T [] → ^T Returns the sum of the elements in the array.
sumBy : ('T → ^U) → 'T [] → ^U Returns the sum of the results generated by applying a function to each element of an array.
toList : 'T [] → 'T list Converts the supplied array to a list.
toSeq : 'T [] → seq<'T> Views the supplied array as a sequence.
tryFind : ('T → bool) → 'T [] → 'T option Returns the first element in the supplied array for which the supplied function returns true. Returns *None *if no such element exists.
tryFindIndex : ('T → bool) → 'T [] → int option Returns the index of the first element in an array that satisfies the supplied condition.
tryPick : ('T → 'U option) → 'T [] → 'U option Applies the supplied function to successive elements of the supplied array, and returns the first result where the function returns Some(x) for some x. If the function never returns Some(x),* None *is returned.
unzip : ('T1* 'T2) [] → 'T1 [] *'T2 [] Splits an array of tuple pairs into a tuple of two arrays.
unzip3 : ('T1* 'T2 'T3) [] → 'T1 [] 'T2 [] *'T3 [] Splits an array of tuples of three elements into a tuple of three arrays.
zeroCreate : int → 'T [] Creates an array whose elements are initially set to the default value Unchecked.defaultof<'T>.
zip : 'T1 [] → 'T2 [] → ('T1* 'T2) [] Combines two arrays into an array of tuples that have two elements. The two arrays must have equal lengths; otherwise, ArgumentException is raised.
zip3 : 'T1 [] → 'T2 [] → 'T3 [] → ('T1 'T2 113 'T3) [] Combines three arrays into an array of tuples that have three elements. The three arrays must have equal lengths; otherwise, ArgumentException is raised.

次のセクションでは、これらの機能の一部の使用方法について説明します。

関数を使用して配列を作成する

Arrayモジュールには、配列を最初から作成するいくつかの関数があります。

  • Array.empty 関数は、新しい空の配列を作成します。
  • Array.create 関数は、指定されたサイズの配列を作成し、すべての要素を指定された値に設定します。
  • Array.init 関数は、要素を生成する次元と関数を指定して、配列を作成します。
  • Array.zeroCreate 関数は、すべての要素がゼロ値に初期化される配列を作成します。
  • Array.copy 関数は、既存の配列からコピーされた要素を含む新しい配列を作成します。
  • Array.sub 関数は、配列の部分範囲から新しい配列を生成します。
  • Array.append 関数は、2つの既存の配列を組み合わせて新しい配列を作成します。
  • Array.choose 関数は、新しい配列に含める配列の要素を選択します。
  • Array.collect 関数は、既存の配列の各配列要素に対して指定された関数を実行し、関数によって生成された要素を収集して、それらを新しい配列に結合します。
  • Array.concat 関数は配列のシーケンスを取り、それらを単一の配列に結合します。
  • Array.filter 関数はブール条件関数を取り、条件が真である入力配列からの要素のみを含む新しい配列を生成します。
  • Array.rev 関数は、既存の配列の順序を逆にして新しい配列を生成します。

次の例は、これらの機能を示しています-

例1

( *using create and set* )
let array1 = Array.create 10 ""
for i in 0 .. array1.Length - 1 do
   Array.set array1 i (i.ToString())
for i in 0 .. array1.Length - 1 do
   printf "%s " (Array.get array1 i)
printfn " "

( *empty array* )
let array2 = Array.empty
printfn "Length of empty array: %d" array2.Length

let array3 = Array.create 10 7.0
printfn "Float Array: %A" array3

( *using the init and zeroCreate* )
let array4 = Array.init 10 (fun index -> index * index)
printfn "Array of squares: %A" array4

let array5 : float array = Array.zeroCreate 10
let (myZeroArray : float array) = Array.zeroCreate 10
printfn "Float Array: %A" array5

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

0 1 2 3 4 5 6 7 8 9
Length of empty array: 0
Float Array: [|7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0; 7.0|]
Array of squares: [|0; 1; 4; 9; 16; 25; 36; 49; 64; 81|]
Float Array: [|0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0; 0.0|]

例2

( *creating subarray from element 5* )
( *containing 15 elements thereon* )

let array1 = [| 0 .. 50 |]
let array2 = Array.sub array1 5 15
printfn "Sub Array:"
printfn "%A" array2

( *appending two arrays* )
let array3 = [| 1; 2; 3; 4|]
let array4 = [| 5 .. 9 |]
printfn "Appended Array:"
let array5 = Array.append array3 array4
printfn "%A" array5

( *using the Choose function* )
let array6 = [| 1 .. 20 |]
let array7 = Array.choose (fun elem -> if elem % 3 = 0 then
   Some(float (elem))
      else
   None) array6

printfn "Array with Chosen elements:"
printfn "%A" array7

(*using the Collect function *)
let array8 = [| 2 .. 5 |]
let array9 = Array.collect (fun elem -> [| 0 .. elem - 1 |]) array8
printfn "Array with collected elements:"
printfn "%A" array9

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

Sub Array:
[|5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19|]
Appended Array:
[|1; 2; 3; 4; 5; 6; 7; 8; 9|]
Array with Chosen elements:
[|3.0; 6.0; 9.0; 12.0; 15.0; 18.0|]
Array with collected elements:
[|0; 1; 0; 1; 2; 0; 1; 2; 3; 0; 1; 2; 3; 4|]

配列の検索

*Array.find* 関数はブール関数を取り、関数がtrueを返す最初の要素を返します。それ以外の場合はKeyNotFoundExceptionを発生させます。
*Array.findIndex* 関数は、要素自体ではなく要素のインデックスを返すことを除いて、同様に機能します。

次の例はこれを示しています。

マイクロソフトは、この興味深いプログラム例を提供します。これは、完全な正方形と完全な立方体の両方である、与えられた数の範囲の最初の要素を見つけます-

let array1 = [| 2 .. 100 |]
let delta = 1.0e-10
let isPerfectSquare (x:int) =
   let y = sqrt (float x)
   abs(y - round y) < delta

let isPerfectCube (x:int) =
   let y = System.Math.Pow(float x, 1.0/3.0)
   abs(y - round y) < delta

let element = Array.find (fun elem -> isPerfectSquare elem && isPerfectCube elem) array1

let index = Array.findIndex (fun elem -> isPerfectSquare elem && isPerfectCube elem) array1

printfn "The first element that is both a square and a cube is %d and its index is %d." element index

あなたがプログラムをコンパイルして実行すると、次の出力が得られます-

The first element that is both a square and a cube is 64 and its index is 62.