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

Doug Bagley <>
Sun Oct 8 03:02:28 CEST 2000


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.

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

Thanks,
Doug

%%% -*- mode: erlang -*-
% cat.erl
% instructions:
% erl -compile cat.erl
% cat datafile | erl -noshell -s cat main

-module(cat).
-export([main/0]).

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