gpt4 book ai didi

ruby - Ruby 的 block 语法的起源是什么?

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

Ruby 有一个有趣的 block 语法(管道之间的参数后跟一系列语句):

[1, 2, 3].each do |x|
puts x
end

Rust 也使用类似的语法:

arr.sort_by_key(|a| {
let intermediate_value = some_function(a);
intermediate_value + 10
});

我想知道这种语法是否早于 Ruby(特别是在管道之间放置参数,我相信我在其他地方见过但不确定在哪里),如果是,哪些语言使用它?

我相信 Smalltalk 也使用管道,但用于对象初始化,我在 Google 上找不到任何其他示例。

谢谢!

最佳答案

Ruby 的创造者“Matz”表示,Ruby 的设计灵感来自 Perl、Smalltalk、Eiffel、Ada 和 Lisp。

从这个列表中,我认为它很可能来自 Smalltalk、Eiffel 和 Lisp。示例:

小谈话

#(1 2 3 4 5) inject: 0 into: [:sum :number | sum + number]
#(1 2 3 4 5) fold: [:product :number | product * number]

口齿不清

(let ((data #(1 2 3 4 5)))     ; the array
(values (reduce #'+ data) ; sum
(reduce #'* data))) ; product
(loop for i in '(1 2 3 4 5) sum i)

埃菲尔铁塔

class
APPLICATION

create
make

feature {NONE}

make
local
test: ARRAY [INTEGER]
do
create test.make_empty
test := <<5, 1, 9, 7>>
io.put_string ("Sum: " + sum (test).out)
io.new_line
io.put_string ("Product: " + product (test).out)
end

sum (ar: ARRAY [INTEGER]): INTEGER
-- Sum of the items of the array 'ar'.
do
across
ar.lower |..| ar.upper as c
loop
Result := Result + ar [c.item]
end
end

product (ar: ARRAY [INTEGER]): INTEGER
-- Product of the items of the array 'ar'.
do
Result := 1
across
ar.lower |..| ar.upper as c
loop
Result := Result * ar [c.item]
end
end

end

关于ruby - Ruby 的 block 语法的起源是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55737735/

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