为了做相当于Python列表的理解,我正在做以下事情:
some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点......也许有一个方法调用?
在我的Python学习书中,当我阅读时List Comprehension,作者有一个小说明解释:
Python的列表理解是语言对函数式编程概念的支持的一个例子.
我已经去维基百科阅读有关函数式编程的内容.但我很难想象,因为我List Comprehension在维基页面上没有看到任何关联和这个概念.
请给我一个明确的解释(如果能,请给我一些关于Java或C#函数式编程的例子:D)
我刚开始学习Erlang,并且非常喜欢他们的列表理解语法,例如:
Weather = [{toronto, rain}, {montreal, storms}, {london, fog}, {paris, sun}, {boston, fog}, {vancounver, snow}].
FoggyPlaces = [X || {X, fog} <- Weather].
Run Code Online (Sandbox Code Playgroud)
在这种情况下,FoggyPlaces将评估为"伦敦"和"波士顿".
在Ruby中执行此操作的最佳方法是什么?
例如,像一个数组(很常见,我相信):
weather = [{city: 'toronto', weather: :rain}, {city: 'montreal', weather: :storms}, {city: 'london', weather: :fog}, {city: 'paris', weather: :sun}, {city: 'boston', weather: :fog}, {city: 'vancounver', weather: :snow}]
Run Code Online (Sandbox Code Playgroud)
我现在最好的是:
weather.collect {|w| w[:city] if w[:weather] == :fog }.compact
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,我必须调用compact删除nil值,并且示例本身不像Erlang那样可读.
而更在二郎示例中,city和weather是原子.我甚至不知道如何在Ruby中获得有意义且看起来很好的东西.
我不得不开始学习C作为我正在做的项目的一部分.我已经开始在其中处理'euler'问题并且遇到第一个问题.我必须找到1000或以下3或5的所有倍数的总和.有人可以帮助我.谢谢.
#include<stdio.h>
int start;
int sum;
int main() {
while (start < 1001) {
if (start % 3 == 0) {
sum = sum + start;
start += 1;
} else {
start += 1;
}
if (start % 5 == 0) {
sum = sum + start;
start += 1;
} else {
start += 1;
}
printf("%d\n", sum);
}
return(0);
}
Run Code Online (Sandbox Code Playgroud)