I am very busy recently. Work from morning till night. Do not write a blog. You don't even have time to read a blog. Although I have always wanted to gossip about JavaScript, And I have betrayed the revolution, I can't leave it blank. However, I can't help but reprint the wonderful code.
The cause is that everyone is familiar with the fold function, which is also a common inject () function in Ruby: it gives the starting value and overwrites the values in a collection. For example, the starting value 0 is given, and the accumulative array [1, 2, 3, 4, 5] is given:
[1, 2, 3, 4, 5].inject(0){|sum, n| sum = sum + n}
With fold, there is the opposite unfold: map a single object to the collection. For example
10.unfold { |n| n-1 unless n == 1 }.inspect => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]10.class.unfold(&:superclass).inspect => [Fixnum, Integer, Numeric, Object]
Its implementation is also surprisingly beautiful: Through recursion, The unfold call is rewritten as an array operation. The style of the Term Rewriting System:
class Object
def unfold &block
block.call(self).unfold(&block).unshift(self)
end
end
class NilClass
def unfold &block
[]
end
end
Examples are the easiest way to illustrate how amazing this implementation is. We manually execute 3. unfold {| n-1 unless n = 1 }:
- We use block to refer to the {| n-1 unless n = 1} in the above formula }. According to the definition of unfold, the above formula becomes block. Call (3). unfold (& Block). unshift (3)
- Execute block. Call (3) to get 2, so we get 2. unfold (& Block). unshift (3)
- According to the definition, we get block. Call (2). unfold (& Block). unshift (2). unshift (3)
- Run block. Call (2). We get 1. unfold (& Block). unshift (2). unshift (3)
- Based on the definition, we get block. Call (1). unfold (& Block). unshift (1). unshift (2). unshift (3)
- The result of block. Call (1) is nil, so we get nil. unfold (& Block). unshift (1). unshift (2). unshift (3)
- Nil has prepared the definition of unfold, so we get []. unshift (1). unshift (2). unshift (3), that is, [3, 2, 1.
Now, you can see the discussion here.