I would do something like
let last n xs = xs |> List.rev |> Seq.take n |> List.ofSeq |> List.rev
I am not sure about turning a list to a sequence and back though. Is this how you do it F#?
Use the del statement with list slicing to remove the last N elements from a list, e.g. del my_list[len(my_list) - n:] The del statement will remove the last N elements from the original list.
Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end. As we want second to last element in list, use -2 as index.
Method #2 : Using islice() + reversed() The inbuilt functions can also be used to perform this particular task. The islice function can be used to get the sliced list and reversed function is used to get the elements from rear end.
tailn n xs = drop (length xs - n) xs ---- take away what you don't want from the front of the list, leaving what you do want, the remainder of the list.
Taking the last N items is equivalent to skipping the first (length - N) items, so for a Sequence as input (and output), you could do something like:
let last n xs = Seq.skip ((Seq.length xs) - n) xs
(or, with piping, let last n xs = xs |> Seq.skip (Seq.length xs - n)
and for a List as input (and output) you could do:
let last n xs = List.toSeq xs |> Seq.skip (xs.Length - n) |> Seq.toList
or by defining both, just pipe it to the sequence one:
let lastList n xs = List.toSeq xs |> last n |> Seq.toList
Alternatively, this can be achieved by (tail) recursively applying Tail as so:
let rec last n xs =
if List.length xs <= n then xs
else last n xs.Tail
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With