How to get a list?

I have a list like [1..12] , and I would like to get a fragment as [4..9] . I don't know how I can do this, I'm new to F #. I do not know if there is a built-in method for this, but I would like to know a manual way.

+4
source share
3 answers

To immediately answer your question: how do you take part of the list? Matching samples.

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

 let range min max xs = let rec skipWhile f = function | x::xs when fx -> skipWhile f xs | xs -> xs let rec takeWhile f acc = function | x::xs when fx -> 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] 
+4
source
 [1..12] |> List.filter (fun x -> x >= 4 && x <= 9) 

or

 [1..12] |> Seq.skip 3 |> Seq.take 6 |> Seq.toList 

Lists do not support slice, but if you use an array, you can also do this:

 [|1..12|].[3..8] 

(note 3..8 instead of 4..9 due to indexing based on 0)

+8
source

Assuming you are using an Ocaml-like subset of F #, you probably want to use the standard List module, perhaps its filter function.

Otherwise, you can use the tail recursive function with matching.

+1
source

Source: https://habr.com/ru/post/1495537/


All Articles