吃了大力丸的Ruby:unfold的實現

來源:互聯網
上載者:User

最近奇忙。從早到晚工作。別說寫部落格,連讀部落格都 沒有時間。雖然一直想八卦一下JavaScript那濃眉大眼的也背叛革命了這件大事,卻抽不出空。不過看到這麼精彩的代碼,還是忍不住轉載。

起因是這樣的:大家都熟悉fold函數,也就是Ruby裡常用的inject()函數:給出起始值,把某個Collection裡的值疊加上去。比如說,給出起始值0,累加數組[1, 2, 3, 4, 5]: 

[1, 2, 3, 4, 5].inject(0){|sum, n| sum = sum + n}

有了fold,便有相反的unfold:把單個的對象映射到Collection上。比如說 

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]

它的實現也出奇地漂亮:通過遞迴把unfold調用改寫為數組操作。頗有term rewriting系統的風範: 

class Object
def unfold &block
block.call(self).unfold(&block).unshift(self)
end
end


class NilClass
def unfold &block
[]
end
end
用例子最容易說明這段實現的驚豔之處。我們手工執行3.unfold{|n| n - 1 unless n ==1}:
  1. 我們用block指代上式裡的{|n| n - 1 unless n == 1}。根據unfold的定義,上式變為block.call(3).unfold(&block).unshift(3)
  2. 執行block.call(3)得到2,於是我們得到2.unfold(&block).unshift(3)
  3. 根據定義,我們得到block.call(2).unfold(&block).unshift(2).unshift(3)
  4. 執行block.call(2),我們得到1.unfold(&block).unshift(2).unshift(3)
  5. 再根據定義,我們得到block.call(1).unfold(&block).unshift(1).unshift(2).unshift(3)
  6. block.call(1)的結果是nil,所以我們得到nil.unfold(&block).unshift(1).unshift(2).unshift(3)
  7. nil早準備好了unfold的定義,於是我們得到[].unshift(1).unshift(2).unshift(3),也就是[3, 2, 1]了。

現在胃口被吊起來的老大們可以看這裡的討論了。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.