rank1
rank1

Reputation: 1038

How to aggregate over many lists in F#

In F# at some point I have many lists (the actual number of them differs for input data) and I want to make an aggregation over all those lists (let say addition for simplification). So what I want to achieve is the same what List.map2 or List.map3 does but for bigger number of lists.

How can I approach it? I was wondering if this is possible to do with List.scan?

Upvotes: 1

Views: 680

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243051

You can use List.reduce and do something like this:

> let lists = [[1;2;3]; [1;2;3]; [1;2;3]]
val lists : int list list = (...)

> lists |> List.reduce (List.map2 (+));;
val it : int list = [3; 6; 9]

What does this do?

  • List.reduce takes a list of values (here the value is int list) and it aggregates them into a single value using a function that says how to merge two values. So in this case, we need to give it a function int list -> int list -> int list and it will call it on the first and the second list, then on the result and the third list (and so on).

  • The argument List.map2 (+) is a function of the right type - it takes two lists and performs pairwise sum of the two lists. This is really just a shortcut for writing something like:

    lists |> List.reduce (fun list1 list2 -> 
      List.map2 (fun a b -> a + b) list1 list2)
    

Upvotes: 9

Related Questions