F#, why can't I access the “Item” member

匆匆过客 提交于 2019-12-06 04:55:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!