在F#中将字符串列表转换为浮点数/整数 [英] Converting a list of strings into floats/ints in F#
问题描述
是否有一种快速简单的方法将整个字符串列表转换为浮点数或整数
并将它们像F#中那样加在一起?
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);
}
推荐答案
类似的东西应该具有相同的效果:
Something like this should have the same effect:
let sum = list |> Seq.map System.Int32.Parse |> Seq.sum
F#似乎不支持引用上的方法int
,所以我不得不使用 System.Int32
。
F# doesn't seem to support referring to the method on int
so I had to use System.Int32
instead.
在F#中,该类型 seq
是.NET IEnumerable
的别名,因此此代码适用于数组,列表等。
In F# the type seq
is an alias for the .NET IEnumerable
, so this code works on arrays, lists etc.
请注意以无点样式使用 Parse
-没有参数的函数可以直接用作另一个需要该类型的函数。在这种情况下, Seq.map
具有以下类型:
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>
由于 System.Int32.Parse
具有输入 string-> int
, Seq.map System.Int32.Parse
具有类型 seq< string> -> seq< int>
。
And since System.Int32.Parse
has type string -> int
, Seq.map System.Int32.Parse
has type seq<string> -> seq<int>
.
这篇关于在F#中将字符串列表转换为浮点数/整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!