How to get a piece of a list?

f#

Solution

To give an immediate answer to your question: how do you take a piece of a list? Pattern matching.

You can use pattern matching to write a function that extracts a range from a list. The basic algorithm is skip each element of the list while E < Min, then take each element while E <= Max. Something like this:

let range min max xs =
  let rec skipWhile f = function
    | x::xs when f x -> skipWhile f xs
    | xs -> xs
  let rec takeWhile f acc = function
    | x::xs when f x -> takeWhile f (x::acc) xs
    | _ -> List.rev acc
  xs
  |> skipWhile ((>) min)
  |> takeWhile ((>=) max) []

[1..12] |> range 4 9
> val it : int list = [4; 5; 6; 7; 8; 9]

Problem

I have a list like `[1..12]` and I would like to get a piece like `[4..9]`. No clue how I can do that, I'm new with F#. I don't know if there is a built-in method for that, but I would like to know the manual way.

Original source