How to do line oriented i/o in constant space?

Robert Virding <>
Mon Oct 9 13:30:03 CEST 2000

Doug Bagley <> writes:
>I wanted to write a small version of the Unix 'cat' command in Erlang.
>The following program works, but it uses memory in proportion to the
>input data size (choosing either the cat1 or cat2 function).  It looks
>like it should take advantage of tail recursion, but I must admit I can
>be easily fooled since I'm new to functional programming and Erlang.

It most definitely should work in constant space as both functions are
tailrecursive.  In R7B cat1/1 and cat2/1 are completely equivalent
(compiled code wil be the same) and which form you choose is a matter of

>What would be the best way to do I/O in constant space in Erlang?

Depends what you want to do with the data.  The method Tobbe shows is
MUCH better if you just want to shuffle data through the system, getting
lists is better if you want to process the data.  A middle way would be 
to get binaries and then convert to lists as required.


Robert Virding                          Tel: +46 (0)8 545 55 017
Bluetail AB                             Email: 
S:t Eriksgatan 44                       WWW:
SE-112 32 Stockholm, SWEDEN
"Folk säger att jag inte bryr mig om någonting, men det skiter jag i".

>%%% -*- mode: erlang -*-
>% cat.erl
>% instructions:
>% erl -compile cat.erl
>% cat datafile | erl -noshell -s cat main
>main() ->
>    %cat1(io:get_line('')),
>    cat2(io:get_line('')),
>    halt(0).
>cat1(Line) ->
>    case Line of
>	eof  -> true;
>	_ -> io:put_chars(Line),
>	     cat1(io:get_line(''))
>    end.
>cat2(eof) ->
>    true;
>cat2(Line) ->
>    io:put_chars(Line),
>    cat2(io:get_line('')).

More information about the erlang-questions mailing list