Sunday, December 21, 2008

Pattern matching for string and list in erlang

Earlier I wrote a post on how to distinguish string from list. Steve and Justinpointed that my approach will not work for a list of anythingg other than string.

Here is what I am trying to solve. I have a main configuratin file and client specific configuration files. Client specific configuration file can override or add more values from main configuration file. If the value in main configuration file is a string, I want the client configuration to override the value of main configuration. If the value in main configuration is a list, I want to append the list from the client configuration to the main configuration.

For example, main configuration file is

[{blacklist, ["foo.com", "aaa.com"]},
{source_host, "http://www.bar.com"}].

and client configuration file is

[{blacklist, [ "bar.com" ]},
{source_host, "http://www.something.com"}].

After merging above 2 configuration, I want the final configuration to look like,

[{blacklist, [ "foo.com", "aaa.com", "bar.com" ]},
{source_host, "http://www.something.com"}].

The code reading the configuration files and merging them does not know the first element of the tuple ahead of time. The code is generic to read a file of list of tuples and merge the values to generate the final configuration.

Since Erlang implement string as a list, using is_list guard for a function will not work. If anybody has solved this problem earlier, please comment on this blog.

2 comments:

Unknown said...

I'm assuming that the configuration files will use Erlang syntax. If this assumtion correct you can use file:consult/1 or the erl_scan and erl_parse modules to parse the content and then work with erlang data structures when trying to merge the configuration? If you want some other syntax in your configuration file you should probably implement a parser for it to separate parsing the text file and actually merge configuration.

Dude From Mangalore said...

Oscar, Thanx for the comment. But unfortunately it did not answer my question. What I am really trying to solve is to differentiate a list from string.

Book Promotion