2016年1月30日土曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Lua (プログラミング言語)

Seven More Languages in Seven Weeks (Bruce Tate (著)、Ian Dees (著)、Frederic Daoud (著)、Jack Moffitt (著)、Pragmatic Bookshelf)のChapter 1(Lua)、Day 2(Tables All the Way Down)、Do (Hard)(No. 1199).を取り組んでみる。

Do (Hard)(No. 1199)

コード(Emacs)

function retry(count, body)   
   while count > 0 do
      print('count: ' .. count)
      local generator = coroutine.create(body)
      succeeded, value = coroutine.resume(generator)
      if value then
         print(value)
         count = count - 1
      else
         count = 0
      end      
   end   
end

function f()
   local r = math.random()
   print('random: ' .. r)
   if r > 0.2 then
      coroutine.yield('Something bad happend')
   end
   print('Succeeded')
end

for i = 1, 10 do
   print('--------------------------------------------------')
   retry(5, f)
end

入出力結果(Terminal)

$ lua sample_hard.lua
--------------------------------------------------
count: 5
random: 0.84018771676347
Something bad happend
count: 4
random: 0.39438292663544
Something bad happend
count: 3
random: 0.78309922339395
Something bad happend
count: 2
random: 0.79844003310427
Something bad happend
count: 1
random: 0.91164735751227
Something bad happend
--------------------------------------------------
count: 5
random: 0.19755136920139
Succeeded
--------------------------------------------------
count: 5
random: 0.33522275555879
Something bad happend
count: 4
random: 0.76822959445417
Something bad happend
count: 3
random: 0.27777471067384
Something bad happend
count: 2
random: 0.55396995553747
Something bad happend
count: 1
random: 0.47739705163985
Something bad happend
--------------------------------------------------
count: 5
random: 0.62887092446908
Something bad happend
count: 4
random: 0.36478447262198
Something bad happend
count: 3
random: 0.51340090995654
Something bad happend
count: 2
random: 0.9522297247313
Something bad happend
count: 1
random: 0.91619506757706
Something bad happend
--------------------------------------------------
count: 5
random: 0.63571172766387
Something bad happend
count: 4
random: 0.71729692909867
Something bad happend
count: 3
random: 0.14160255528986
Succeeded
--------------------------------------------------
count: 5
random: 0.60696887597442
Something bad happend
count: 4
random: 0.016300571616739
Succeeded
--------------------------------------------------
count: 5
random: 0.24288677051663
Something bad happend
count: 4
random: 0.13723157672212
Succeeded
--------------------------------------------------
count: 5
random: 0.80417675385252
Something bad happend
count: 4
random: 0.15667908918113
Succeeded
--------------------------------------------------
count: 5
random: 0.40094439405948
Something bad happend
count: 4
random: 0.12979044672102
Succeeded
--------------------------------------------------
count: 5
random: 0.1088088019751
Succeeded
$

0 コメント:

コメントを投稿

Comments on Google+: