Skip to content

Instantly share code, notes, and snippets.

@cararemixed
Created July 10, 2013 02:35
Show Gist options
  • Save cararemixed/5963026 to your computer and use it in GitHub Desktop.
Save cararemixed/5963026 to your computer and use it in GitHub Desktop.
This is derived from a demo I gave to explain the ins and outs of Erlang list construction literals at the NYC user group.
-module(cons).
-export([demo/0, reveal/1]).
format(Form, Terms) -> lists:flatten(io_lib:format(Form, Terms)).
%% Show that all lists are actually a construction of pairs
%% (aka. the "cons" operator [ L | R ]) by converting terms
%% into an explicit string form via pattern matching.
reveal([Left|Right]) ->
"[" ++ reveal(Left) ++ " | " ++ reveal(Right) ++ "]";
reveal(Other) -> format("~p", [Other]).
demo() ->
Examples = [
{[1,2,3], "list of numbers"},
{[a, b, c], "list of atoms"},
{[[a,b,c], [1,2,3]], "nested lists"},
{[a | [b | [c | []]]], "a -> b -> c -> nil"},
{[a, b | [c]], "mixed syntax"},
{"Hello!", "strings are lists"},
{["a", "b", "c"], "nested lists/strings will match"},
{[<<"a">>, <<"b">>, <<"c">>], "binaries are not lists"},
{[l|r], "symmetry"},
{[[[[] | 1] | 2] | 3], "improper left associative list construction"}
],
ShowExample = fun({L, Description}) ->
io:format("~s:~n ~p -> ~p~n", [Description, L, reveal(L)])
end,
lists:foreach(ShowExample, Examples).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment