I’m writing a chat bot which needs to reply to user input.
My current code is something like this:
def reply(msg) do cond do: String.match?(msg, ~r/hi/) -> "Hello user!" String.match?(msg, ~r/bye/) -> "Bye user!" String.match?(msg, ~r/name/) -> "My name is Chatbot" true -> "Sorry, I didn't understand you" end end
You can see that this scales poorly.
I’d like to create multiple
reply(msg) functions with a kind of guard that matches the regex.
def reply(msg) when String.match?(msg, ~r/hi/) do "Hello user!" end def reply(msg) when String.match?(msg, ~r/bye/) do "Bye user!" end ...
I know this can’t be done since guard functions are limited. In Python I can do this by decorating the function. I assume that something could be done in Elixir with Macros, but I don’t know which is the most elixir-y way to solve this.
Right now, it works with the giant
cond but as bot actions turn more complex I could end up with a function with 100s of lines, that’s why I’d want to split it.