Last active
November 21, 2022 07:45
-
-
Save andrewsardone/6969549 to your computer and use it in GitHub Desktop.
Elixir doctests
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
defmodule AndrewEnum do | |
@moduledoc """ | |
A reimplementation of the standard `Enum` module. | |
""" | |
@doc """ | |
Invokes the given `fun` for each item in the `collection`. | |
Returns `:ok`. | |
## Examples | |
iex> AndrewEnum.each([], fn -> end) | |
:ok | |
iex> AndrewEnum.each([1, 2, 3], fn(x) -> Process.put(:andrew_enum_test_each, x * 2) end) | |
iex> Process.get(:andrew_enum_test_each) | |
6 | |
Note that the above example as a doctest is a bit contrived, but I | |
need *some* kind of side effect to assert on for AndrewEnum.each. I | |
stole the idea of stuffing state into the process dictionary via the | |
`Process` module from `elixir/enum_test.exs`. | |
Another note, but this doesn't *completely* replicate Enum.each since | |
it only accepts a list and not *any* `Enumerable` collection. | |
""" | |
def each([], _), do: :ok | |
def each([head|tail], fun) do | |
fun.(head) | |
each(tail, fun) | |
end | |
end | |
defmodule AndrewEnum.Test do | |
use ExUnit.Case | |
doctest AndrewEnum | |
end | |
# ❯ mix test | |
# .. | |
# | |
# Finished in 0.06 seconds (0.06s on load, 0.00s on tests) | |
# 2 tests, 0 failures |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment