F# Friday – The Seq.skip Function

The opposite of Seq.take is Seq.skip. Seq.skip, as the name suggests, skips the first n items of the sequence and returns a new sequence that starts with element n + 1:

let xs = seq [1..10]
let skipped5 = xs |> Seq.skip 5
// val skipped5 : seq<int> =
//   [6; 7; 8; 9; 10]

One of most obvious applications of Seq.skip is to pair it with Seq.take or Seq.truncate to page through a set of records. Perhaps you have a list of books:

type Book = 
    { Title : string
      Author : string }

let books = 
    seq [
        { Title = "Wuthering Heights"
          Author = "Emily Bronte" }
        { Title = "Jane Eyre"
          Author = "Charlotte Bronte" }
        { Title = "Agnes Grey"
          Author = "Anne Bronte" }
        { Title = "The Scarlet Letter"
          Author = "Nathaniel Hawthorne" }
        { Title = "Silas Marner"
          Author = "George Eliot" }
        { Title = "1984"
          Author = "George Orwell" }
        { Title = "Billy Budd"
          Author = "Herman Melville" }
        { Title = "Moby Dick"
          Author = "Herman Melville" }
        { Title = "The Great Gatsby"
          Author = "F. Scott Fitzgerald" }
        { Title = "Tom Sawyer"
          Author = "Mark Twain" }
    ]

If each page shows three books, and the user wants to see the records on page three, skip the first two pages’ worth of records, and take the next three records:

let perPage = 3
let page = 3
let records = 
    books
    |> Seq.skip ((page - 1) * perPage)
    |> Seq.take perPage

// val records : seq<Book> =
//   [{Title = "Billy Budd";
//     Author = "Herman Melville";};
//    {Title = "Moby Dick";
//     Author = "Herman Melville";};
//    {Title = "The Great Gatsby";
//     Author = "F. Scott Fitzgerald";}]

Unfortunately, like Seq.take, if you ask the sequence for more elements than it contains, it throws an exception:

let oops = seq [1..5]
           |> Seq.skip 6 
           |> printfn "%A"
// System.InvalidOperationException: 
//   The input sequence has an insufficient
//   number of elements.

2 thoughts on “F# Friday – The Seq.skip Function”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.