1

My objective is to find the total amount of sun for the following years - 1960,1970,1980,1990,2000,2010. The data comes from a txt file and year, month, maxt, mint, afday, rain and sun have already been defined and take the relevant element from the tuple, then it ignores the rest.

// Example
let sun  (_,_,_,_,_,_,t) = t

I have found the total amount of sun for the year 1960. However, I am not sure how to find the remaining years.

let Q6 =
    ds |> List.filter (fun s-> year(s)=1960)
       |> List.sumBy sun

The above method is a boolean so wouldn't work for multiple years, what is the best method? I believe the answer should be like this:

val Q6 : float list = [1434.4; 1441.8; 1393.0; 1653.0; 1599.5; 1510.2]
ildjarn
  • 62,044
  • 9
  • 127
  • 211
lewishh
  • 53
  • 6
  • Please don't use a seven-component tuple to group simple data that doesn't have an obvious order. A record, or another type with named members, should be much more readable than the huge tuple. – Vandroiy Feb 26 '15 at 13:49

1 Answers1

4

You can group them before applying the sum:

let Q6 =
    let years = [1960;1970;1980;1990;2000;2010]
    // or let years = [1960 .. 10 .. 2010]
    ds |> Seq.filter (fun value -> List.exists ((=) (year value)) years)
       |> Seq.groupBy year
       |> Seq.map (fun (year, values) -> year, Seq.sumBy sun values)
       |> Seq.toList

Here you will get something like:

val Q6 : (int * float) list = [(1960, 1434.4); (1980, 1441.8)]

If you don't want to have the year in the results you can remove the year , from the lambda.

Gus
  • 25,839
  • 2
  • 51
  • 76