你能从管道中的长生不老药中的结构中提取数据吗?
Can you extract data from a struct in elixir in a pipe?
我有一个函数可以将输入字符串散列到一个包含数字的列表中,并将它放在一个结构中。
def hash_input(input) do
hexList = :crypto.hash(:md5, input)
|> :binary.bin_to_list
%Identicon.Image{hex: hexList}
end
我想编写一个测试来确保 hexList 中的每个元素都是整数,所以我想到了这个:
test "Does hashing produce a 16 space large array with numbers? " do
input = Identicon.hash_input("løsdjflksfj")
%Identicon.Image{hex: numbers} = input
assert Enum.all?(numbers, &is_integer/1) == true
我尝试使用管道运算符(为了我自己的学习)编写测试,但我无法使用模式匹配提取管道中的十六进制属性。
test "Does hashing produce a 16 space large array with numbers? With pipe " do
assert Identicon.hash_input("løsdjflksfj")
|> %Identicon.Image{hex: numbers} = 'i want the input to the pipe operator to go here' # How do you extract the hex-field?
|> Enum.all?(&is_integer/1) == true
我正在努力实现的目标是否可行?
你不能真的像那样通过管道传输,但你可以做的是通过管道传输到 Map.get
以获得 :hex
,然后将其通过管道传输到 Enum.all?
.
"løsdjflksfj"
|> Identicon.hash_input()
|> Map.get(:hex)
|> Enum.all?(&is_integer/1)
如果你真的想在你的管道中使用模式匹配,请注意你需要做的是确保沿着管道传递的只是你想要传递的值(在你的情况下 numbers
).
因此,您还可以使用一个匿名函数,该函数接收 Identicon.hash_input/1
的结果并生成 :hex
的值:
"løsdjflksfj"
|> Identicon.hash_input()
|> (fn %{hex: numbers} -> numbers end).()
|> Enum.all?(&is_integer/1)
注意匿名函数后面的.()
。这意味着它应该在那里被调用。
但我会说 Map.get
方法更惯用。
我有一个函数可以将输入字符串散列到一个包含数字的列表中,并将它放在一个结构中。
def hash_input(input) do
hexList = :crypto.hash(:md5, input)
|> :binary.bin_to_list
%Identicon.Image{hex: hexList}
end
我想编写一个测试来确保 hexList 中的每个元素都是整数,所以我想到了这个:
test "Does hashing produce a 16 space large array with numbers? " do
input = Identicon.hash_input("løsdjflksfj")
%Identicon.Image{hex: numbers} = input
assert Enum.all?(numbers, &is_integer/1) == true
我尝试使用管道运算符(为了我自己的学习)编写测试,但我无法使用模式匹配提取管道中的十六进制属性。
test "Does hashing produce a 16 space large array with numbers? With pipe " do
assert Identicon.hash_input("løsdjflksfj")
|> %Identicon.Image{hex: numbers} = 'i want the input to the pipe operator to go here' # How do you extract the hex-field?
|> Enum.all?(&is_integer/1) == true
我正在努力实现的目标是否可行?
你不能真的像那样通过管道传输,但你可以做的是通过管道传输到 Map.get
以获得 :hex
,然后将其通过管道传输到 Enum.all?
.
"løsdjflksfj"
|> Identicon.hash_input()
|> Map.get(:hex)
|> Enum.all?(&is_integer/1)
如果你真的想在你的管道中使用模式匹配,请注意你需要做的是确保沿着管道传递的只是你想要传递的值(在你的情况下 numbers
).
因此,您还可以使用一个匿名函数,该函数接收 Identicon.hash_input/1
的结果并生成 :hex
的值:
"løsdjflksfj"
|> Identicon.hash_input()
|> (fn %{hex: numbers} -> numbers end).()
|> Enum.all?(&is_integer/1)
注意匿名函数后面的.()
。这意味着它应该在那里被调用。
但我会说 Map.get
方法更惯用。