fork download
  1. # Swift's closure
  2. # https://d...content-available-to-author-only...e.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
  3.  
  4.  
  5. class String
  6. class << self
  7. def __unfoldl_rec__(b, &block)
  8. return self.to_enum(:__unfoldl_rec__, b) unless block_given?
  9.  
  10. if (pair = yield b).nil?
  11. ''
  12. else
  13. a, b1 = pair
  14.  
  15. __unfoldl_rec__(b1, &block) + a
  16. end
  17. end
  18.  
  19.  
  20. def __unfoldl_until__(b)
  21. return self.to_enum(:__unfoldl_until__, b) unless block_given?
  22.  
  23. s = ''
  24. until (pair = yield b).nil?
  25. a, b = pair
  26.  
  27. s += a
  28. end
  29.  
  30. s
  31. end
  32.  
  33.  
  34. def __unfoldl_loop__(b)
  35. return self.to_enum(:__unfoldl_loop__, b) unless block_given?
  36.  
  37. loop.inject([b, '']) { |(b1, s), _|
  38. if (pair = yield b1).nil?
  39. break s
  40. else
  41. a, b2 = pair
  42.  
  43. [b2, a + s]
  44. end
  45. }
  46. end
  47.  
  48.  
  49. # alias unfoldl __unfoldl_rec__
  50. alias unfoldl __unfoldl_until__
  51. # alias unfoldl __unfoldl_loop__
  52. end
  53. end
  54.  
  55.  
  56.  
  57. DigitNames = {
  58. 0 => "Zero", 1 => "One", 2 => "Two", 3 => "Three", 4 => "Four",
  59. 5 => "Five", 6 => "Six", 7 => "Seven", 8 => "Eight", 9 => "Nine"
  60. }
  61. Numbers = [16, 58, 510]
  62.  
  63.  
  64. puts '==== Internal enumerator ===='
  65. strings = Numbers.map { |number|
  66. String.unfoldl(number) { |num|
  67. if num <= 0
  68. nil
  69. else
  70. [DigitNames[num % 10], num / 10]
  71. end
  72. }
  73. }
  74.  
  75. for s in strings
  76. puts s
  77. end
  78.  
  79.  
  80. puts
  81. puts '==== External enumerator (aka. Generator) ===='
  82. strings = Numbers.map { |number|
  83. for num in String.unfoldl(number)
  84. if num <= 0
  85. nil
  86. else
  87. [DigitNames[num % 10], num / 10]
  88. end
  89. end
  90. }
  91.  
  92. for s in strings
  93. puts s
  94. end
Success #stdin #stdout 0.02s 7432KB
stdin
Standard input is empty
stdout
==== Internal enumerator ====
SixOne
EightFive
ZeroOneFive

==== External enumerator (aka. Generator) ====
SixOne
EightFive
ZeroOneFive