首页 > 解决方案 > 将字符串与 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

输出总是错误的。为什么?

标签: elixir

解决方案


您正在使用Enum.take_randomwhich 返回一个列表。那当然永远不会匹配一个字符串。

对您的代码的一些改进:

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

推荐阅读