不知道如何创建一个结构,其中默认值来自同一模块中的一个函数。以下是我的例子:
defmodule Poker.Deck do
alias Poker.Deck.Card
@values [:a, :"2", :"3", :"4", :"5", :"6", :"7", :"8", :"9", :"10", :j, :q, :k]
@suits [:spades, :clubs, :diamonds, :hearts]
def new do
(for x <- @values, y <- @suits, do: %Card{value: x, suit: y})
|> Enum.shuffle
end
# Putting this at the top or bottom still doesn't solve the problem...
defstruct deck: __MODULE__.new, used: [], in_hand: []
end
编译时返回以下内容:
== Compilation error on file lib/poker/deck.ex ==
** (UndefinedFunctionError) undefined function: Poker.Deck.new/0
Poker.Deck.new()
lib/poker/deck.ex:14: (module)
(stdlib) erl_eval.erl:657: :erl_eval.do_apply/6
(elixir) src/elixir.erl:163: :elixir.erl_eval/2
(elixir) src/elixir.erl:156: :elixir.eval_forms/4
答案 0 :(得分:3)
你可以利用defstruct简单地定义一个函数__struct__()
的事实,它返回一个包含__struct__
键的映射来实现这个目的:
defmodule Poker.Deck do
alias Poker.Deck.Card
@values [:a, :"2", :"3", :"4", :"5", :"6", :"7", :"8", :"9", :"10", :j, :q, :k]
@suits [:spades, :clubs, :diamonds, :hearts]
def new do
(for x <- @values, y <- @suits, do: %Card{value: x, suit: y})
|> Enum.shuffle
end
def __struct__() do
%{__struct__: __MODULE__, deck: __MODULE__.new(), used: [], in_hand: []}
end
end
运行这个为%Poker.Deck{}
的每个新实例提供了一个新的混乱套牌。