Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Erlang vs Ruby列表理解_Ruby_Erlang_List Comprehension - Fatal编程技术网

Erlang vs Ruby列表理解

Erlang vs Ruby列表理解,ruby,erlang,list-comprehension,Ruby,Erlang,List Comprehension,我刚开始学习Erlang,非常喜欢他们的列表理解语法,例如: Weather = [{toronto, rain}, {montreal, storms}, {london, fog}, {paris, sun}, {boston, fog}, {vancounver, snow}]. FoggyPlaces = [X || {X, fog} <- Weather]. 到目前为止,我得到的最好结果是: weather.collect {

我刚开始学习Erlang,非常喜欢他们的列表理解语法,例如:

Weather = [{toronto, rain}, {montreal, storms}, {london, fog}, {paris, sun}, {boston, fog}, {vancounver, snow}].                          
FoggyPlaces = [X || {X, fog} <- Weather].
到目前为止,我得到的最好结果是:

weather.collect {|w| w[:city] if w[:weather] == :fog }.compact
但是在本例中,我必须调用
compact
来删除
nil
值,并且示例本身不像Erlang那样可读


更重要的是,在Erlang示例中,
city
weather
都是原子。我甚至不知道如何在Ruby中获得有意义且看起来很好的东西。

首先,您的数据结构是不等价的。与您的Erlang示例等效的Ruby数据结构更像

weather = [[:toronto, :rain], [:montreal, :storms], [:london, :fog], 
            [:paris, :sun], [:boston, :fog], [:vancouver, :snow]]
weather.select(&:foggy?).map(&:city)
其次,是的,Ruby既没有列表理解,也没有模式匹配。因此,这个例子可能会更复杂。您的列表首先过滤所有雾城市,然后投影名称。让我们在Ruby中做同样的事情:

weather.select {|_, weather| weather == :fog }.map(&:first)
# => [:london, :boston]
然而,Ruby以对象为中心,但您使用的是抽象数据类型。如果使用更面向对象的数据抽象,代码可能看起来更像

weather = [[:toronto, :rain], [:montreal, :storms], [:london, :fog], 
            [:paris, :sun], [:boston, :fog], [:vancouver, :snow]]
weather.select(&:foggy?).map(&:city)

这还不算太糟糕,是吗?

这是一个常见问题:,.erlang非常具有声明性和符号性,非常接近于humanErlang元组与Ruby哈希不等价?+1表示一点关于对象的信息。直接翻译通常不是惯用翻译。不,Erlang
dict
s等同于Ruby
Hash
es。Ruby中确实没有元组的直接等价物,最接近的是数组。@caarlos0不要让大括号语法欺骗你:元组与Hashes.hm的数据类型不同,明白了吗。。我还没有看到dicts,我只是开始:)谢谢你的简单解释。