Scy
Scy

Reputation: 245

Building list of tuples from list in Erlang

I am trying to read content from a file and then organize it into a list of tuples. I have read the file into a list of numbers, however it seems to skip numbers immediately after newlines, how to prevent this behaviour? I am guaranteed a file of even number of characters.

-module(brcp).
-export([parse_file/1]).

parse_file(Filename) ->
    read_file(Filename).

read_file(Filename) ->
    {ok, File} = file:read_file(Filename),
    Content = unicode:characters_to_list(File),
    build_tuples([begin {Int,_}=string:to_integer(Token), Int end|| Token<-string:tokens(Content," /n/r")]).

build_tuples(List) ->
    case List of 
        [] -> [];
        [E1,E2|Rest] -> [{E1,E2}] ++ build_tuples(Rest)
    end.    

Here is a sample input file:

1 7 11 0
1 3 5 0 7 0
1 8 10 0 1 11
99 0

Upvotes: 2

Views: 1072

Answers (1)

Greg
Greg

Reputation: 8340

-module(tuples).
-export([parse/0]).

parse() ->
    {ok, File} = file:read_file("tuples.txt"),
    List = binary:split(File, [<<" ">>, <<"\t">>, <<"\n">>], [global, trim_all]),
    io:format("~p~n", [List]),
    build_tuples(List, []).

build_tuples([X,Y|T], Acc) ->
    build_tuples(T, [{X,Y}|Acc]);
build_tuples([X|T], Acc) ->
    build_tuples(T, [{X, undefined}|Acc]);
build_tuples([], Acc) ->
    lists:reverse(Acc).

The text file I used is almost as yours but I added tabs and multiple spaces to make it more realistic:

1 7  11 0
1 3 5 0 7 0
    1 8 10   0 1 11
99  0

You can of course convert binaries to integers when adding them to tuples with erlang:binary_to_integer/1. The binary:split/3 function used in the code parses all empty characters (tabs, spaces, new lines) to empty binaries and then trim_all ignores them. You can skip them if your input is always well-formed. Result:

14> tuples:parse().
[<<"1">>,<<"7">>,<<"11">>,<<"0">>,<<"1">>,<<"3">>,<<"5">>,<<"0">>,<<"7">>,<<"0">>,<<"1">>,<<"8">>,<<"10">>,<<"0">>,<<"1">>,<<"11">>,<<"99">>,<<"0">>]
[{<<"1">>,<<"7">>},{<<"11">>,<<"0">>},{<<"1">>,<<"3">>},{<<"5">>,<<"0">>},{<<"7">>,<<"0">>},{<<"1">>,<<"8">>},{<<"10">>,<<"0">>},{<<"1">>,<<"11">>},{<<"99">>,<<"0">>}]

Upvotes: 1

Related Questions