F#: Create a list that contains the head of all the lists, in the list

Viewed 78

I am trying to create a function that takes the head of all the lists in the list ([[]]). So far I've found out how to take all the first ints of all the lists in the list, but I can't seem to make that into a list in the same function.

let isTable (llst : list<list<'a>>) : bool =
    List.forall (fun (elem : list<'a>) -> not elem.IsEmpty && elem.Length = elem.Length) llst


let a = [[1;2;3];[4;5;6]]
printfn "%A" (isTable a)     

List.iter (fun x -> printfn "%A " (List.head x)) a

Can anyone help here?

1 Answers

You can use List.map to apply List.head that you already found to each list.

let a = [[1;2;3];[4;5;6]]
let collectHeads l = List.map List.head l
printfn "%A" (collectHeads a)  // [1,4]

Unlike List.head, List.map is a higher order function and expects a function as a parameter. Expected function should take an element of the list's type and return another element. It happens that List.head does just that: it takes a list as input and return's it's head as resulting element.

Related