我正在参加Ruby Koans的练习,我发现以下我发现真的无法解释的Ruby怪癖:
array = [:peanut, :butter, :and, :jelly]
array[0] #=> :peanut #OK!
array[0,1] #=> [:peanut] #OK!
array[0,2] #=> [:peanut, :butter] #OK!
array[0,0] #=> [] #OK!
array[2] #=> :and #OK!
array[2,2] #=> [:and, :jelly] #OK!
array[2,20] #=> [:and, :jelly] #OK!
array[4] #=> nil #OK!
array[4,0] #=> [] #HUH?? Why's that?
array[4,100] #=> [] #Still HUH, but consistent with previous one
array[5] #=> nil #consistent with array[4] #=> nil
array[5,0] #=> nil #WOW. Now I don't understand anything anymore...
Run Code Online (Sandbox Code Playgroud)
那么为什么 …
使用Python中的列表,我可以使用以下代码返回它的一部分:
foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
half = len(foo) / 2
foobar = foo[:half] + bar[half:]
Run Code Online (Sandbox Code Playgroud)
由于Ruby在数组中做了所有事情,我想知道是否有类似的东西.
在SICP练习2.26中,给出了这个方案代码:
(define x (list 1 2 3))
(define y (list 4 5 6))
Run Code Online (Sandbox Code Playgroud)
然后给出这个利弊电话:
(cons x y)
Run Code Online (Sandbox Code Playgroud)
我预计会产生一对列表,((1 2 3) (4 5 6))但解释器会给出
((1 2 3) 4 5 6)
一个包含4个元素的列表,第一个是列表.为什么y对待不同?我已经尝试查找其他SICP答案的解释,但找不到令人满意的东西.那么,任何Scheme/Lisp专家都能对这方面的缺点有所了解吗?提前感谢您的任何见解.