문제

Is there a quick and simple way to convert an entire list of strings into floats or integers and add them together similar to this in F#?

foreach(string s in list)
{
    sum += int.Parse(s);
}
도움이 되었습니까?

해결책 2

Something like this should have the same effect:

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

F# doesn't seem to support referring to the method on int so I had to use System.Int32 instead.

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

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

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

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

다른 팁

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

let sum = list |> Seq.sumBy int

This does pretty much the same thing - the int function is a generic conversion that converts anything to an integer (and it works on strings too). The sumBy function is a combination of map and sum that first projects all elements to a numeric value and then sums the results.

Technically, there are at least 3 different approaches:

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

let sum = Seq.sumBy int list

2) For instructional purposes, it may be interesting to see how closely one can simulate C# behavior in F#; for instance, using a reference cell type:

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

3) Same idea as 2), but using a byref pointer type:

let inline (+=) (x:_ byref) y = x <- x + y
let mutable sum = 0
for s in list do &sum += int s
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top