elixir - 将字符串与 Elixir 列表中的随机值进行比较的问题
问题描述
defmodule Takes do
def rnd do
lst = ["rock", "paper", "scissors"]
tke = Enum.take_random(lst, 1)
IO.puts "#{tke}"
IO.puts "#{List.first(lst)}"
IO.puts "#{tke == List.first(lst)}"
end
end
Takes.rnd
输出总是错误的。为什么?
解决方案
您正在使用Enum.take_random
which 返回一个列表。那当然永远不会匹配一个字符串。
对您的代码的一些改进:
defmodule Takes do
def rnd do
lst = ["rock", "paper", "scissors"]
tke = Enum.random(lst) # this will return a single item, not a list
IO.inspect(tke) # no need for string interpolation, also if you used inspect before
# you would see that `tke` was indeed a list
IO.puts hd(lst) # hd and tl are both very useful functions, check them out
tke == hd(lst) # the last statement in a function is the return value (and when
# using `iex` will be printed)
end
end
Takes.rnd
推荐阅读
- javascript - 很想知道如何更改子字符串的颜色并使文本的其余颜色保持不变
- docker - Docker for Windows 绑定卷在 Windows 10 中挂载空卷
- c# - 后台工作人员仍然冻结 ui
- typescript - TypeGraphQL 使用 TypeORM 的 findAndCount 方法
- javascript - 反应模式没有关闭 onClick
- keras - 如何使用功能 api 将另一个输入层添加到多输入模型?
- mongodb - MongoDB 未找到数据:返回未定义
- javascript - 如何将访问令牌和商店名称传递给 Shopify API 节点新对象
- css - 如何在 w3school css 框架中自定义 w3-button-hover 类?
- oauth-2.0 - 使用 OAuth 2.0 进行授权时,如何防止未经批准的 3rd Party SPA 访问资源?