質問

F#コードにはタプルがあります:

let myWife=("Tijana",32)

タプルの各メンバーに個別にアクセスしたい。たとえば、私が達成したいことはできません

Console.WriteLine("My wife is {0} and her age is {1}",myWife[0],myWife[1])

このコードは明らかに機能しません。私が達成したいことを収集できると思います。

役に立ちましたか?

解決

年齢を不変にすることで、妻の老化を防ぎたいですか? :)

2つのメンバーのみを含むタプルの場合、 fst および snd を使用して、ペアのメンバーを抽出できます。

let wifeName = fst myWife;
let wifeAge = snd myWife;

長いタプルの場合、他の変数にタプルを展開する必要があります。たとえば、

let _, age = myWife;;
let name, age = myWife;;

他のヒント

別の非常に便利なことは、パターンマッチング(「let」バインディングを使用して要素を抽出する場合と同様)が、関数を記述するときなど、他の状況で使用できることです:

let writePerson1 person =
  let name, age = person
  printfn "name = %s, age = %d" name age

// instead of deconstructing the tuple using 'let', 
// we can do it in the declaration of parameters
let writePerson2 (name, age) = 
  printfn "name = %s, age = %d" name age

// in both cases, the call is the same
writePerson1 ("Joe", 20)
writePerson2 ("Joe", 20)

関数fstを使用して最初の要素を取得し、sndを使用して2番目の要素を取得できます。独自の「3番目」の関数を記述することもできます:

let third (_, _, c) = c

詳細はこちら: F#言語リファレンス、タプル

一定の長さのアンパック関数を書くこともできます:

let unpack4 tup4 ind =
    match ind, tup4 with
    | 0, (a,_,_,_) -> a
    | 1, (_,b,_,_) -> b
    | 2, (_,_,c,_) -> c
    | 3, (_,_,_,d) -> d
    | _, _ -> failwith (sprintf "Trying to access item %i of tuple with 4 entries." ind) 

または

let unpack4 tup4 ind =
    let (a, b, c, d) = tup4
    match ind with
    | 0 -> a
    | 1 -> b
    | 2 -> c
    | 3 -> d
    | _ -> failwith (sprintf "Trying to access item %i of tuple with 4 entries." ind) 
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top