问题
In F#, why can't I access the "Item" member on the Array here:
let last (arr:System.Array) =
let leng = arr.Length
arr.[leng-1] // Error: Field, constructor or member "Item" is not defined.
回答1:
Can you try this?
let last (arr:_[]) =
let leng = arr.Length
arr.[leng-1]
回答2:
This seems to be a general dotnet thing. Looking up the documentation I see
The Array class is the base class for language implementations that support arrays. However, only the system and compilers can derive explicitly from the Array class. Users should employ the array constructs provided by the language.
回答3:
Also, note that in F# you'd typically use an immutable List:
let last (stuff: _ list) =
let l = stuff.Length
stuff.[l]
But if you're using a list, you'd use a more efficient algorithm; F# lists are linked lists:
let rec last = function
| hd :: [] -> hd
| hd :: tl -> last tl
| _ -> failwith "Empty list."
来源:https://stackoverflow.com/questions/16968060/f-why-cant-i-access-the-item-member