The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Continuations are so much easier to grasp than 2ch and Japanese

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Eigen Class

Posts: 358
Nickname: eigenclass
Registered: Oct, 2005

Eigenclass is a hardcore Ruby blog.
Continuations are so much easier to grasp than 2ch and Japanese Posted: Nov 16, 2005 5:49 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Eigen Class.
Original Post: Continuations are so much easier to grasp than 2ch and Japanese
Feed Title: Eigenclass
Feed URL: http://feeds.feedburner.com/eigenclass
Feed Description: Ruby stuff --- trying to stay away from triviality.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Eigen Class
Latest Posts From Eigenclass

Advertisement

ko1 (of YARV fame) pointed me to an interesting question on 2ch (a large Japanese BBS).

Given some #open() and #close() methods, you can define trivially

def open_block(fn)
  fh = open(fn)
  yield fh
  close(fh)
end 

which accepts a block, passes the file handler corresponding to a given filename and closes it when done (you'd normally use an ensure clause, but the original message carried the above definition). This is a standard idiom. Now, given a working #open_block, can you define #open and #close?

As I read that, I knew it would involve callcc. #open was trivial, #close seemed harder. Actually hard enough to deserve being done. I was game.

It was pretty late (~1AM), but callcc is always fun and anyway it would only take a few minutes to solve, so I quickly came up with

def _open(name); puts "open: #{name}"; "IO<#{name}>" end
def _close(name); puts "close: #{name}" end

def open_block(fn); fh = _open(fn); yield fh; _close(fh); end

open_block("hoge"){|x| puts "Got #{x}" }

def open(x)
  callcc do |cc|
    r = nil
    open_block(x) do |fh|
      r = callcc do |cc2|
        fh.instance_variable_set("@_closecc", cc2)
        cc.call(fh)
      end
    end
    r.call
  end
end

def close(x)
  callcc do |cc|
    x.instance_variable_get("@_closecc").call(cc)
  end
end

a = open("foo")
puts "----"
close(a)
puts "end"

Read more...

Read: Continuations are so much easier to grasp than 2ch and Japanese

Topic: Zen and the Art of Pure TDD Previous Topic   Next Topic Topic: Why Java (presumably) won't go anywhere soon

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use