Prima di tutto, si sta utilizzando let
come se fosse una dichiarazione di mutare una variabile, ma non è questo il caso. In F #, let
viene utilizzato per dichiarare un nuovo valore (che potrebbe nascondere qualsiasi valore precedente con lo stesso nome). Se si desidera scrivere codice usando mutazione, allora avete bisogno di usare qualcosa come:
let c = a + b // declare new local value
l.Add(c)
a <- b // mutate value marked as 'mutable'
b <- c // .. mutate the second value
Il secondo problema con il codice è che si sta cercando di mutare F # lista con l'aggiunta di elementi ad esso - F # liste sono immutabili quindi, una volta creati, non è possibile modificarli (in particolare, non esiste un membro Add
!). Se si voleva scrivere questo utilizzando mutazione, si potrebbe scrivere:
let fabList =
// Create a mutable list, so that we can add elements
// (this corresponds to standard .NET 'List<T>' type)
let l = new ResizeArray<_>([1;2])
let mutable a = 1
let mutable b = 2
while l.[l.Count - 1] < 400 do
let c = a + b
l.Add(c) // Add element to the mutable list
a <- b
b <- c
l |> List.ofSeq // Convert any collection type to standard F# list
Ma, come altri già notato, scrivere il codice in questo modo non è la soluzione # idiomatica F. In F #, si utilizzano elenchi e ricorsioni immutabili anziché cicli (ad esempio while
). Ad esempio:
// Recursive function that implements the looping
// (it takes previous two elements, a and b)
let rec fibsRec a b =
if a + b < 400 then
// The current element
let current = a + b
// Calculate all remaining elements recursively
// using 'b' as 'a' and 'current' as 'b' (in the next iteration)
let rest = fibsRec b current
// Return the remaining elements with 'current' appended to the
// front of the resulting list (this constructs new list,
// so there is no mutation here!)
current :: rest
else
[] // generated all elements - return empty list once we're done
// generate list with 1, 2 and all other larger fibonaccis
let fibs = 1::2::(fibsRec 1 2)
fonte
2010-05-16 22:43:14
Sì, lo stai facendo male. Stai usando un linguaggio di programmazione funzionale come quello procedurale. Prova a farlo senza usare 'while' o altri costrutti di loop simili all'inizio. –