Convert string list to float / int in F #

Is there a simple and easy way to convert the entire list of strings to floats or integers and add them together in F #?

foreach(string s in list) { sum += int.Parse(s); } 
+7
f # c # -to-f #
source share
3 answers

Something like this should have the same effect:

 let sum = list |> Seq.map System.Int32.Parse |> Seq.sum 

F # doesn't seem to support invoking a method on an int , so I had to use System.Int32 instead.

In F #, the seq type is an alias for .NET IEnumerable , so this code works with arrays, lists, etc.

Pay attention to the use of Parse in the " Parse " style - a function without its argument can be used directly as an argument to another function that expects this type. In this case, Seq.map has this type:

 ('a -> 'b) -> seq<'a> -> seq<'b> 

And since System.Int32.Parse is of type string -> int , Seq.map System.Int32.Parse is of type seq<string> -> seq<int> .

+14
source share

If you want to aim for the minimum number of characters, then you can simplify the solution sent by Ganesh, something like this:

 let sum = list |> Seq.sumBy int 

This is almost the same - the int function is a general conversion that converts something to an integer (and it also works with strings). The sumBy function is a combination of map and sum , which first projects all the elements on a numerical value, and then sums up the results.

+14
source share

Technically, there are at least 3 different approaches:

1) The Seq.sum or sumBy approach described in other answers is the canonical way to get the sum in F #:

 let sum = Seq.sumBy int list 

2) For educational purposes, it may be interesting to see how closely you can simulate the behavior of C # in F #; for example using a reference cell type:

 let inline (+=) xy = x := !x + y let sum = ref 0 for s in list do sum += int s 

3) The same idea as 2), but using the pointer type byref:

 let inline (+=) (x:_ byref) y = x <- x + y let mutable sum = 0 for s in list do &sum += int s 
0
source share

All Articles