'trues and length of bool list f#

Directly using recursion, write a function truesAndLength : bool list -> int * int that returns both the length of the list (in the first component of the pair), and the number of elements of the list that are true (in the second component). Your function must only iterate over the elements of the list once. (Do not use any of the functions from the List module.)

this is my code so far:

let rec length bs =
    match bs with
    | [] -> 0
    | b::bs -> 1 + length bs

let rec trues bs = 
    match bs with
    | [] -> 0
    | b::bs -> if b = true then 1 + trues bs else trues bs

let truesandlength bs =
    let l = length bs
    let t = trues bs
    (l, t)

truesandlength [true; true; false]

This works by im iterating through the list 2 times, i can't figure out how to iterate only 1. Any tips?

f#


Solution 1:[1]

let rec truesAndLength bs = 
  let sum a b = (fst a + fst b, snd a + snd b)
  match bs with
  | [] -> 0, 0
  | head::tail ->
    if head then sum (1,1) (truesAndLength tail) else sum (1, 0) (truesAndLength tail)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mattyboo