gpt4 book ai didi

ruby - Erlang 与 Ruby 列表理解

转载 作者:数据小太阳 更新时间:2023-10-29 07:23:58 25 4
gpt4 key购买 nike

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

Weather = [{toronto, rain}, {montreal, storms}, {london, fog}, {paris, sun}, {boston, fog}, {vancounver, snow}].                          
FoggyPlaces = [X || {X, fog} <- Weather].

在这种情况下,FoggyPlaces 的计算结果将是“london”和“boston”。

在 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}]

到目前为止我得到的最好的是:

weather.collect {|w| w[:city] if w[:weather] == :fog }.compact

但在这种情况下,我必须调用 compact 来删除 nil 值,并且示例本身不像 Erlang 那样可读。

更重要的是,在 Erlang 示例中,cityweather 都是原子。我什至不知道如何在 Ruby 中获得像这样有意义且看起来不错的东西。

最佳答案

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

weather = [[:toronto, :rain], [:montreal, :storms], [:london, :fog], 
[:paris, :sun], [:boston, :fog], [:vancouver, :snow]]

其次,是的,Ruby 没有列表理解或模式匹配。因此,示例可能更复杂。你的列表理解首先过滤掉所有有雾的城市,然后投影名称。让我们在 Ruby 中做同样的事情:

weather.select {|_, weather| weather == :fog }.map(&:first)
# => [:london, :boston]

但是,Ruby 以对象为中心,而您使用的是抽象数据类型。使用更面向对象的数据抽象,代码可能看起来更像

weather.select(&:foggy?).map(&:city)

还不错吧?

关于ruby - Erlang 与 Ruby 列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13378987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com