What do you think about pre and post condition checks in Elixir?
I’ve just started learning Elixir and can see how guards are similar to pre-condition checks. Is there anything that could be used for post-condition checks?
Last night I realised the pipe operator could be used (abused?) to help implement post-condition checks and wrote this marcro:
defmacro ensure input, pattern1, pattern2 do
quote do
case unquote(input) do
unquote(pattern1) -> unquote(input)
unquote(pattern2) -> unquote(input)
_ -> raise PostConditionError
end
end
end
It would be used like:
def is_food(input) do
case input do
"Cheese" -> true
"Beer" -> {:error, "Item is not food"}
"Phone" -> false
end
|> ensure(true, {:error, _reason})
end
A is_food("Phone") call would result in a PostConditionError being raised.
Thoughts?






















