how to get the value of the last element of a List? I've noted that List.hd (or .Head) return an item, while List.tl (or .Tail) returns a List.
Is rev the List and get the hd the only way around? Thanks.
how to get the value of the last element of a List? I've noted that List.hd (or .Head) return an item, while List.tl (or .Tail) returns a List.
Is rev the List and get the hd the only way around? Thanks.
In general, if you need to do this, you're doing something wrong. Since F# lists are single-linked, accessing the last element is costly -
O(N)
, where N is size oflist
. Try to rewrite your algorithm so that you always access the first element, not the last (which isO(1)
). If you cannot do so, chances are good that your choice oflist
for a data structure wasn't correct in the first place.Agreed, not so efficient to get the last element of
list
, or any other "enumerable" sequence. That said, this function already exists in theSeq
module,Seq.last
.I think you can just write
You can call List.Head to get the first element of a list, such that the below expression evaluates to true:
However, calling List.Tail will return every element in the list after the first element, such that the below expression is true:
Like some other people have mentioned, there isn't an efficient way in F# to get the tail end of a list, basic lists just aren't built with that functionality in mind. If you really want to get the last element you're going to have to reverse your list first, and then take the new head (which was the previous tail).
Below code worked fine with me, I've an array of integers, want to start from the 5th item, then take it minus the item number
The code used is:
As a novice F# developer, I don't see what the harm is in doing the following
Imperative in nature? Yes but no need for recursion.