Last active
February 16, 2022 03:21
-
-
Save hunterwilhelm/3330dcd6c8c612dc42c33fd1c6138ca3 to your computer and use it in GitHub Desktop.
Erlang: Pretty print nested dictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% @author Hunter Wilhelm | |
-module(prettyprintdict). | |
-export([pretty_print_dictionary/1]). | |
%%%-------- | |
%%% helper functions | |
%%%-------- | |
%% @doc The <kbd>isdict/1</kbd> function is a helper function that returns true if the | |
%% parameter is a dictionary. This function might not work in future updates of erlang if they | |
%% change how a dictionary is represented internally. | |
isdict(DictCand) when is_tuple(DictCand) andalso element(1, DictCand) =:= dict -> | |
true; | |
isdict(_NotDict) -> | |
false. | |
%%%-------- | |
%%% print functions | |
%%%-------- | |
%% @doc The <kbd>pretty_print_entries/2</kbd> function prints out the values of | |
%% the list if they are not dictionaries, otherwise, it increases the | |
%% indentation and pretty prints the sub dictionary. | |
pretty_print_entries([], _) -> ok; | |
pretty_print_entries([{Key, Value} | Entries], Indentation) -> | |
case is_atom(Key) of | |
true -> io:format("~s~p~n", [["| " || _ <- lists:seq(1, Indentation)], Key]); | |
_ -> io:format("~s~s~n", [["| " || _ <- lists:seq(1, Indentation)], [Key]]) | |
end, | |
case isdict(Value) of | |
true -> pretty_print_dictionary(Value, Indentation + 1); | |
false -> io:format("~s~p~n", [["|-" || _ <- lists:seq(1, Indentation + 1)], Value]) | |
end, | |
pretty_print_entries(Entries, Indentation). | |
%% @doc The <kbd>pretty_print_dictionary/2</kbd> function pretty prints a dictionary. | |
pretty_print_dictionary(Dict, Indentation) -> | |
Entries = dict:to_list(Dict), | |
pretty_print_entries(Entries, Indentation). | |
%%%-------- | |
%%% facade/public functions | |
%%%-------- | |
%% @doc The <kbd>pretty_print_dictionary/1</kbd> function pretty prints a dictionary. | |
pretty_print_dictionary(Dict) -> | |
pretty_print_dictionary(Dict, 0). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment