There's another cool feature of the @moduledoc
and @doc
attributes and that is what's called
doctesting. That is, the lines in our comments that look similar to iex
sessions can be used as tests where the output return value is the expected result.
Let's return to our flatten project from earlier.
We can add some @doc
comments to the function, and add what would look similar to an iex
session of us manually testing the function, but in fact, would be tests run by the mix
test.
Open the flatten.ex
file from earlier and add the @doc
attribute:
defmodule Flatten do @doc """ Flatten an arbitrarily nested lists ## Examples iex> Flatten.flatten [[1, 2], [3], [4, 5]] [1, 2, 3, 4, 5] iex> Flatten.flatten [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] """ def flatten([]), do: [] def flatten([h|t]) when is_list(h), do: h ++ flatten(t) def flatten([h|t]), do: [h] ++ flatten(t) end
Next, open the flatten_test.exs
file as well and add the following line...