A191919
A191919

Reputation: 3442

F# sum two sequences by element

I am looking for a way to sum two sequences by element in F#.

For example, if I have these two sequences:

let first = seq [ 183.24; 170.15;174.17]
let second = seq [25.524;24.069;24.5]

I want to get the following result:

third list = [208.764;194.219;198.67]

What would be the simplest or the best way to achieve this?

Upvotes: 4

Views: 463

Answers (2)

Gus
Gus

Reputation: 26174

You can use the zip function :

let third = Seq.zip first second |> Seq.map (fun (x, y) -> x + y)

It will create a new sequence with a tuple where the first element is from first and second form second, then you can map and apply the addition of both elements.

As pointed in the comments, map2 is another option, we could say that map2 is equivalent to zip followed by map.

Upvotes: 8

FoggyFinder
FoggyFinder

Reputation: 2220

The easies way to do this - use Seq.map2

let first = seq  [ 183.24; 170.15;174.17]
let second = seq [25.524;24.069;24.5]
//seq [208.764; 194.219; 198.67]
let third = Seq.map2 (+) first second

Upvotes: 5

Related Questions