以下代码在Haskell中.我如何在C#中编写类似的功能?
squareArea xs = [pi * r^2 | r <- xs]
Run Code Online (Sandbox Code Playgroud)
只是为了澄清......上面的代码是一个函数,它将包含圆的半径的列表作为输入.表达式计算输入列表中每个圆的面积.
我知道在C#中,我可以通过循环遍历列表并计算列表中每个圆的区域并返回包含圆圈区域的列表来实现相同的结果.我的问题是......上面的代码可以在C#中以类似的方式编写,也许使用lambda表达式或LINQ?
dtb*_*dtb 22
使用Enumerable:
IEnumerable<double> SquareArea(IEnumerable<int> xs)
{
return from r in xs select Math.PI * r * r;
}
Run Code Online (Sandbox Code Playgroud)
要么
IEnumerable<double> SquareArea(IEnumerable<int> xs)
{
return xs.Select(r => Math.PI * r * r);
}
Run Code Online (Sandbox Code Playgroud)
这与Haskell非常接近
squareArea xs = map (\r -> pi * r * r) xs
Run Code Online (Sandbox Code Playgroud)
xs.Select(r => 2 * Math.PI * r * r)
Run Code Online (Sandbox Code Playgroud)
我认为(在我的浏览器中编写代码,而不是编译代码)是右侧.
一般来说,Haskell列表对表单的理解
[e | x1 <- x1s, x2 <- x2s, p]
Run Code Online (Sandbox Code Playgroud)
可能是这样的
x1s.SelectMany(x1 =>
x2s.SelectMany(x2 =>
if p then return Enumerable.Singleton(e) else return Enumerable.Empty))
Run Code Online (Sandbox Code Playgroud)
要么
from x1 in x1s
from x2 in x2s
where p
select e
Run Code Online (Sandbox Code Playgroud)
或者其他的东西.Darn,我现在没有时间修复它,其他人请做(标记为社区Wiki).
| 归档时间: |
|
| 查看次数: |
1124 次 |
| 最近记录: |