[erlang-questions] IO efficiency

Bryan Fink bryan.fink@REDACTED
Mon May 4 15:39:29 CEST 2009


On Sat, May 2, 2009 at 9:34 PM, Mark Selby <mark@REDACTED> wrote:
> I'm using webmachine, and operating over a tree (node, {id, name,
> children = []}).
>
> As far as output goes, appending recursively to a list seems to make
> sense, as it contains the output in the right order. Just keep a depth
> flag going to achieve indented output.
>
> Should I really be rethinking the schema so that the list is in a
> tail-recursive friendly order instead? Or can I
> io:just_write_to_the_browser_now(Str) in some straightforward way?

Hi, Mark.  I'm not completely clear on the exact issue you're trying
to solve, but I have three answers for you anyway.

Answer 0: There is no way to io:just_write_to_the_browser_now/1 in
Webmachine.  The HTTP aspects of wm resources are defined solely by
the input and output of the resource's functions, rather than by their
side effects.  The resource functions do not have access to the port
used to communicate to the browser.

Answer 1: More tail-recursive friendly is probably the right way to
go.  Each content-producing function in your webmachine resource is
expected to return an iolist.  Building up that output, and returning
it in one go will likely make the cleanest-looking code.

Example 1:

to_html(ReqData, Context#ctx{tree=Tree}) ->
    {tree_to_html(Tree), ReqData, Context}.

@spec tree_to_html(tree()) -> iolist()

Answer 2: wrq:append_to_response_body/2 is the closest you'll come to
an io call.  Pass into that function your ReqData and the content you
want to send back, and it will hand you back a new ReqData with that
content ready to send.  Just return the new ReqData from the
webmachine resource function that modified it.

http://bitbucket.org/justin/webmachine/wiki/WebmachineReqData

Example 2:

to_html(ReqData, Context#ctx{tree=Tree}) ->
    {[], append_tree_to_reqdata(ReqData, Tree), Context}.

@spec append_tree_to_reqdata(wrq(), tree()) -> wrq()
@doc At some point this does a few
wrq:append_to_response_body(iolist(), wrq()) calls

-Bryan



More information about the erlang-questions mailing list