Created
April 12, 2011 22:43
-
-
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.
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
-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