Value of the last element of a list

2020-02-12 00:15发布

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.

10条回答
神经病院院长
2楼-- · 2020-02-12 00:15

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 of list. Try to rewrite your algorithm so that you always access the first element, not the last (which is O(1)). If you cannot do so, chances are good that your choice of list for a data structure wasn't correct in the first place.

查看更多
smile是对你的礼貌
3楼-- · 2020-02-12 00:16

Agreed, not so efficient to get the last element of list, or any other "enumerable" sequence. That said, this function already exists in the Seq module, Seq.last.

查看更多
何必那么认真
4楼-- · 2020-02-12 00:17

I think you can just write

list.[0..list.Length-1]
查看更多
三岁会撩人
5楼-- · 2020-02-12 00:19

You can call List.Head to get the first element of a list, such that the below expression evaluates to true:

let lst = [1;2;3;4;5]
List.head lst = 1

However, calling List.Tail will return every element in the list after the first element, such that the below expression is true:

let lst = [1;2;3;4;5]
List.tail lst = [2;3;4;5]

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).

let lst = [1;2;3;4;5]
(List.head (List.rev lst) ) = 5
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-02-12 00:27

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

Sum of [Array(xi) - Array(xi-5)] where i start at 5

The code used is:

series |> Array.windowed 5
       |> Array.fold (fun s x -> 
                            (x |> Array.rev |> Array.head) -  (x |> Array.head) + s) 0
       |> float
查看更多
Melony?
7楼-- · 2020-02-12 00:29

As a novice F# developer, I don't see what the harm is in doing the following

let mylist = [1;2;3;4;5]

let lastValue = mylist.[mylist.Length - 1]

Imperative in nature? Yes but no need for recursion.

查看更多
登录 后发表回答