简体   繁体   中英

Accessing the first elements in a list of Lists [F#]

I'm currently interested in F# as it is different to everything I have used before. I need to access the first element of each list contained within a large list. If I assume that the main list contains 'x' amount of lists that themselves contain 5 elements, what would be the easiest way to access each of the first elements.

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

My desired output would be a new list containing [1;6;11]

Currently I have

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

To then expand on that, how would I then get all of the second elements? Would it be best to create new lists without the first elements (by removing them using a similar function) and then reusing this same function?

You can use map to extract the head element of each child list:

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

let myfirstElements = List.map firstElements listOfLists

I'm using Ocaml's speak with little lookup on F# so this may be inaccurate, but the idea applies.

EDIT : You can also use List.head which makes it more concise and will return a int list instead of int option list . However, it throws an exception if you hits an empty list. Most of the time, I'd avoid using List.head or List.tail in this case.

The easisest way to access the first element in a list is List.head . As you have a list of lists, you just need to List.map 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]

Now if you need to access other elements, you can use List.item or just index into your list with xs.[1] . But please keep in mind, that for large lists this will be inefficient and if you want fast look up use an array.

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

With indexing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM