如何在Elixir中进行模式匹配?

时间:2018-06-08 03:23:00

标签: elixir phoenix-framework

我是elixir的新手,我试图模仿匹配,但似乎无法做到正确。

我有一个已解码的变量,其值为

{:ok,
 %{
   "_id" => "5b162c483d1f3152b7771a18",
   "exp" => 1529286068,
   "iat" => 1528422068,
   "password" => "$2a$10$hlTl8vV0ENjpRxI1tRVAi.Woxx.na36K/lbZm7FrqLoXfzyoVzFia"
 }}

{:error, :invalid_token}

我尝试在这里使用if else语句,但它总是转到if语句

if { decoded, :ok } do
    IO.inspect(decoded)
  else
    IO.puts('The token is invalid');
end

2 个答案:

答案 0 :(得分:4)

在灵药中,a = 1并不意味着我们像其他编程语言一样为变量分配1。

等号表示我们断言左手边等于右手边。 它就像基本的代数。

例如,
iex> a =1
1
iex> 1=a(你不能用非功能语言这样做)
1

在您的示例中,您必须使用模式匹配来匹配元组。

对于您的情况,您可以使用如下所示的模式匹配和案例陈述。

fine = {:ok,
%{
   "_id" => "5b162c483d1f3152b7771a18",
   "exp" => 1529286068,
   "iat" => 1528422068,
   "password" => "pass"
}}

notfine = {:error, :invalid_token}

input = fine # It can be fine or not fine 

case input do
    #Here do pattern matching with incoming tuple
    {:ok,decoded} -> IO.inspect(decoded)
    {:error,decoded} -> IO.puts("The token is invalid")
end

答案 1 :(得分:3)

模式匹配与条件运算符 无关,更多的是,它主要用于以避免使用条件运算符,这些运算符被我们中的一些人认为是邪恶的。< / p>

模式匹配运算符为from glob import glob from itertools import groupby filenames = sorted(glob('*_[0-9][0-9][0-9][0-9].txt')) for k, g in groupby(filenames, key=lambda f: f.rsplit('_', 1)[0]): with open('{}_allyears.txt'.format(k), 'w') as outfile: for filename in g: with open(filename, 'r') as infile: outfile.write(infile.read()) 。当您执行=时,实际上模式匹配 42到[尚未绑定] foo = 42变量。这就是为什么以下内容完全有效:

 
foo

回到你的例子:

foo = 42
42 = foo # will succeed!
#⇒ 42 
:bar = foo # will raise
# ** (MatchError) no match of right hand side value: 42

Elixir将遍历所有case子句,尝试将参数模式匹配到所有子句中。第一个成功的将被执行,尚未绑定的变量将被绑定(在上面的示例中为ok = {:ok, %{ "_id" => "5b162c483d1f3152b7771a18", "exp" => 1529286068, "iat" => 1528422068, "password" => "pass" }} ko = {:error, :invalid_token} value = ok case value do {:ok, decoded} -> IO.inspect decoded, label: "Decoded" {:error, :invalid_token} -> IO.puts "Invalid token" {:error, unknown} -> IO.inspect unknown, label: "Unknown error" end 。)

旁注: Elixir有一个great guidegreat docs,有人可能会考虑阅读它,而不是在不成功的尝试和SO问题上浪费时间。以下是pattern matching的一部分。

相关问题