Converting a list of strings into floats/ints in F#

时光毁灭记忆、已成空白 提交于 2019-12-08 17:38:22

问题


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);
}

回答1:


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>.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/20825237/converting-a-list-of-strings-into-floats-ints-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!