Domanda

Nel codice F # ho una tupla:

let myWife=("Tijana",32)

Voglio accedere a ciascun membro della tupla separatamente. Ad esempio, ciò che voglio raggiungere non posso

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

Questo codice ovviamente non funziona, penso che tu possa raccogliere ciò che voglio ottenere.

È stato utile?

Soluzione

Vuoi impedire a tua moglie di invecchiare rendendo la sua età immutabile? :)

Per una tupla che contiene solo due membri, puoi fst e snd per estrarre i membri della coppia.

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

Per tuple più lunghe, dovrai decomprimere la tupla in altre variabili. Ad esempio,

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

Altri suggerimenti

Un'altra cosa abbastanza utile è che il pattern matching (proprio come quando si estraggono elementi usando " let " binding) può essere usato in altre situazioni, ad esempio quando si scrive una funzione:

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)

È possibile utilizzare la funzione prima per ottenere il primo elemento e snd per ottenere il secondo ekement. Puoi anche scrivere la tua "terza" funzione:

let third (_, _, c) = c

Ulteriori informazioni qui: Riferimento lingua F #, Tuple

Puoi anche scrivere una funzione di decompressione per una certa lunghezza:

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) 

o

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) 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top