Skip to content

Instantly share code, notes, and snippets.

@marcelmeyer
Created April 12, 2011 22:43
Show Gist options
  • Save marcelmeyer/916609 to your computer and use it in GitHub Desktop.
Save marcelmeyer/916609 to your computer and use it in GitHub Desktop.
We all have written code that outputs some string representation of a time duration, like "You were poked 2 minutes ago". That usually involves a lot of if statements. Here it is in Erlang using pattern matching.
-module(time).
-compile([export_all]).
time_to_words({0,0,_}) -> "now";
time_to_words({0,1,_}) -> "1 minute";
time_to_words({0,M,_}) -> integer_to_list(M) ++ " minutes";
time_to_words({1,0,_}) -> "1 hour";
time_to_words({H,0,_}) -> integer_to_list(H) ++ " hours";
time_to_words({H,1,_}) -> integer_to_list(H) ++ "h " ++ "1min";
time_to_words({H,M,_}) -> integer_to_list(H) ++ "h " ++ integer_to_list(M) ++ "mins".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment