首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >你能从管道中的elixir结构中提取数据吗?

你能从管道中的elixir结构中提取数据吗?
EN

Stack Overflow用户
提问于 2020-09-08 19:48:08
回答 1查看 360关注 0票数 0

我有一个函数,它将输入字符串散列到一个带有数字的列表中,并将其放在一个结构中。

代码语言:javascript
复制
def hash_input(input) do
  hexList = :crypto.hash(:md5, input)
        |> :binary.bin_to_list
  %Identicon.Image{hex: hexList}
end

我想写一个测试来确保hexList中的每个元素都是整数,所以我想出了这个:

代码语言:javascript
复制
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

我尝试使用管道操作符(出于学习目的)来编写测试,但我无法通过模式匹配提取管道中的十六进制属性。

代码语言:javascript
复制
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

我想要实现的目标有可能实现吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-08 20:07:37

你不能真的这样做,但是你可以做的是通过管道连接到Map.get来获得:hex,然后再通过管道连接到Enum.all?

代码语言:javascript
复制
"løsdjflksfj"
|> Identicon.hash_input()
|> Map.get(:hex)
|> Enum.all?(&is_integer/1)

如果您真的想在管道中使用模式匹配,请注意,您需要做的是确保沿管道传递的是您想要传递的值(在本例中为numbers)。

因此,您还可以使用一个匿名函数,该函数接受Identicon.hash_input/1的结果并生成:hex的值

代码语言:javascript
复制
"løsdjflksfj"
|> Identicon.hash_input()
|> (fn %{hex: numbers} -> numbers end).()
|> Enum.all?(&is_integer/1)

注意匿名函数后面的.()。这意味着它应该在那里被调用。

但我要说的是,Map.get方法更惯用。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63793270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档