Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I take last N items from a list in F#?

Tags:

f#

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#?

like image 224
Trident D'Gao Avatar asked Sep 07 '13 05:09

Trident D'Gao


People also ask

How to remove last n items from a list Python?

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.

How do I get the last two items in a list Python?

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.

How do you slice the last 5 elements of a list in Python?

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.

How do you take the last N elements of a list Haskell?

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.


1 Answers

Seq + Skip

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

Tail + Recursion

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
like image 76
Chamila Chulatunga Avatar answered Sep 28 '22 16:09

Chamila Chulatunga