Access to the first items in a list of lists [F #]

I am currently interested in F # as it is different from everything that I used before. I need to access the first element of each list contained in a large list. If I assume that the main list contains "x" the number of lists that themselves contain 5 elements, then what will be the easiest way to access each of the first elements.

let listOfLists = [[1; 2; 3; 4; 5]; [6; 7; 8; 9; 10]; [eleven; 12; thirteen; 14; fifteen]]

My desired result would be a new list containing [1; 6; eleven]

I currently have

let rec firstElements list  =
    match list with
    | list[head::tail] -> 
        match head with
        | [head::tail] -> 1st @ head then firstElements tail

To expand later, how could I get all of the second elements? Would it be better to create new lists without the first elements (deleting them with a similar function) and then reusing the same function?

+4
source share
2 answers

You can use a map to retrieve the title element of each child list:

let firstElements li =
  match li with [] -> None | h::_ -> Some h

let myfirstElements = List.map firstElements listOfLists

I use Ocaml with a little search on F #, so this may not be accurate, but the idea applies.

EDIT . You can also use List.headthat makes it more concise and returns int listinstead int option list. However, it throws an exception if you end up on an empty list. In most cases, I would avoid using List.heador List.tail.

+5
source

The easiest way to access the first element of a list is List.head. Since you have a list of lists, you just need List.mapto execute this function:

let listOfLists = [ [1;2;3;4;5]; [6;7;8;9;10]; [11;12;13;14;15] ]

listOfLists 
|> List.map List.head
//val it : int list = [1; 6; 11]

, , List.item xs.[1]. , , , .

listOfLists
|> List.map (List.item 1)
//val it : int list = [2; 7; 12]

:

listOfLists
|> List.map (fun x -> x.[1])
+1

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


All Articles