Lets say that I want to pattern match against text. Specifically, I want to pattern match on the first letter.
For example, how do I create a pattern that would match "about" and "analog" but not "beta"?
I've tried this:
defmodule MatchStick do def doMatch([head | tail]) when head == "a" do 1 end def doMatch([head | tail]) do 0 end end res = MatchStick.doMatch("abcd");
I've also tried character lists:
defmodule MatchStick do def doMatch([head | tail]) when head == 'a' do 1 end def doMatch([head | tail]) do 0 end end res = MatchStick.doMatch('abcd');
Neither worked. What is the proper way to match text?
defmodule MatchStick do def doMatch("a" <> rest) do 1 end def doMatch(_) do 0 end end
You need to use the string concatenation operator seen here
Example:
iex> "he" <> rest = "hello" "hello" iex> rest "llo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With