Elixir fun continues

These last few days I’ve continued the Elixir exercises journey on exercism.io:

Nothing fancy there, but I still picked up a few tricks. So, in no particular order 🙂

If you use map, the ordering of keys is not maintained as with keyword lists.
Also, there is a way to pass anonymous function to pipe as well! Behold:

defmodule Roman do
  @roman_values [
    {1000, "M"},
    {900, "CM"},
    {500, "D"},
    {400, "CD"},
    {100, "C"},
    {90, "XC"},
    {50, "L"},
    {40, "XL"},
    {10, "X"},
    {9, "IX"},
    {5, "V"},
    {4, "IV"},
    {1, "I"}
  ] # using keyowrd list instead of map because ordering is important

  @doc """
  Convert the number to a roman number.
  @spec numerals(pos_integer) :: String.t
  def numerals(0) do
  def numerals(number) do
    @roman_values |> Enum.find(fn({arabic, roman}) -> number >= arabic end) |> fn({arabic, roman}) ->
      roman <> numerals(number - arabic)

Method signature doesn’t have to match the arguments:

defmodule Gigasecond do
  @doc """
  Calculate a date one billion seconds after an input date.
  @spec from({{pos_integer, pos_integer, pos_integer}, {pos_integer, pos_integer, pos_integer}}) :: :calendar.datetime
  def from(datetime) do
      |> :calendar.datetime_to_gregorian_seconds
      |> +(1_000_000_000)
      |> :calendar.gregorian_seconds_to_datetime

Short but sweet and still very much fun 🙂

Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: