defmodule TruthTable do
def generate(formula) do
variables = extract_variables(formula)
values = generate_truth_values(variables)
header = Enum.join(variables, "\t") <> "\t|\t" <> formula
rows =
Enum.map(values, fn values ->
Enum.join(values, "\t") <> "\t|\t" <> eval(formula, variables, values)
end)
[header | rows]
end
defp extract_variables(formula) do
formula
|> String.replace(~r/[^a-z]/, "")
|> String.graphemes()
|> Enum.uniq()
|> Enum.sort()
end
defp generate_truth_values(variables) do
Enum.reduce(variables, [[]], fn variable, acc ->
List.flatten(for value <- [true, false], do: Enum.map(acc, &[value | &1]))
end)
end
defp eval(formula, variables, values) do
evaluated_formula =
Enum.reduce(variables, formula, fn variable, acc ->
String.replace(
acc,
variable,
to_string(Enum.at(values, String.to_charlist(variable) |> hd |> (&1 - ?a)))
)
end)
to_string(eval(evaluated_formula))
end
end
IO.puts(TruthTable.generate("p and q or r"))warning: variable "variable" is unused (if the variable is not meant to be used, prefix it with an underscore)
truth-table-chatgpt.livemd#cell:alheap52a5yijgredsdhxrxug77ermcn:21: TruthTable.generate_truth_values/1
Prompt: Please, can you write a program in Elixir that generates a truth-table for a propositional logic formula?