Skip to content

Instantly share code, notes, and snippets.

@adolfont
Last active April 29, 2023 13:00
Show Gist options
  • Select an option

  • Save adolfont/b850bc5d193e3d2c46e0289084807c21 to your computer and use it in GitHub Desktop.

Select an option

Save adolfont/b850bc5d193e3d2c46e0289084807c21 to your computer and use it in GitHub Desktop.
Truth-table generator written by ChatGPT in Elixir

Truth-table generator written by ChatGPT in Elixir

Code

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment