Value of the last element of a list

前端 未结 10 942
小蘑菇
小蘑菇 2020-12-18 18:55

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

相关标签:
10条回答
  • 2020-12-18 19:04

    Try this function. It uses recursion, though it gets optimised to iteration anyway since it's tail recursion. In any case, it is most likely quicker than reversing the entire list (using List.rev).

    let rec last = function
        | hd :: [] -> hd
        | hd :: tl -> last tl
        | _ -> failwith "Empty list."
    

    The answer of Pavel Minaev is definitely worth taking into account, however. Nonetheless, the algorithm you have requested may be useful in some rare cases, and is the most efficient way to go about the task.

    0 讨论(0)
  • 2020-12-18 19:07

    A more concise version based on Mitch's answer:

    let lastItem = myList |> List.rev |> List.head
    

    The myList list is sent to List.rev function. The result is then processed by List.head

    0 讨论(0)
  • 2020-12-18 19:08

    A quick & dirty way of doing it is by using List.reduce. Assuming the list is called ls,

    let lastElement ls = List.reduce (fun _ i -> i) ls
    

    As for efficiency, I agree with Pavel.

    0 讨论(0)
  • 2020-12-18 19:20

    I think you can just write

    list.[0..list.Length-1]
    
    0 讨论(0)
  • 2020-12-18 19:21

    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.

    0 讨论(0)
  • 2020-12-18 19:21

    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
    
    0 讨论(0)
提交回复
热议问题