elixir - 您可以从管道中的长生不老药中的结构中提取数据吗?
问题描述
我有一个函数,可以将输入字符串散列到一个带有数字的列表中,并将其放在一个结构中。
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
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
方法更惯用。
推荐阅读
- java - 需要帮助将转换后的文本从 serverlet 转换为语音到 jsp 页面
- database - 如何在另一个表的 ID 中的 Postregsql 实体表中插入自动生成的 ID
- r - 观察箱线图中的子分类值
- jquery - 未定义获取文件名列表
- javascript - 排序未应用于对象列表
- c# - 有没有办法在具有 .net 核心的计时器上运行 DI 范围服务?
- python - 需要在代码中放入哪些参数才能正确执行 requests.post 函数?
- angular - 如何返回http请求数据
- tree - 二叉搜索树插入有问题,左树工作正常,右树不行
- swift - 按下按钮后如何使图片出现在单元格中