Unpacking Values from Strings and Tuples
Explore pattern matching with strings and tuples.
Pattern matching is useful for extracting parts of values to variables in a process called destructuring. It’s the primary tool to get part of a string, an item from a list, and a value from the map. We use destructuring together with pattern matching when we’re making two things match. This section will explore pattern matching with several data types and see how we can extract values and make more complex matches.
Matching parts of a string
Strings are a data type that we can use in pattern matching. We can use the <>
operator to check the beginning of a string. It’s useful for checking text organized in key/value pairs. For example, we can match one header pattern in the HTTP protocol. In the following example, we’ll make a simple match to get the credentials part of the following string. A terminal is present at the end of the lesson for you to test out the command.
iex> "Authentication: " <> credentials = "Authentication: Basic dXNlcjpwYXNz"
iex> credentials
#Output -> "Basic dXNlcjpwYXNz"
The only restriction in pattern matching with strings is that we can’t use a variable on the left side of the <>
operator. Consider this example:
iex> first_name <> " Doe" = "John Doe"
#Output -> ** (CompileError) a binary field without size is only allowed at the end of a binary pattern and never allowed in binary generators
Strings are binaries, and <>
is a binary operator. The error means we can’t start our ...