Skip to content

Instantly share code, notes, and snippets.

@adrianomitre
Last active July 29, 2020 22:37
Show Gist options
  • Save adrianomitre/582537f23a1b9f4c39f2fb766b2722d9 to your computer and use it in GitHub Desktop.
Save adrianomitre/582537f23a1b9f4c39f2fb766b2722d9 to your computer and use it in GitHub Desktop.
Heuristic to infer whether a list should be printed as charlist in IEx - An improvement proposal
defmodule HeuristicInference do
@moduledoc """
Heuristic to infer whether a list should be printed as charlist in IEx.
An improvement proposal.
"""
def should_print_as_charlist?([]) do
true
end
def should_print_as_charlist?([head | tail]) do
should_print_head_as_charlist =
cond do
is_integer(head) -> List.ascii_printable?([head])
is_list(head) -> should_print_as_charlist?(head)
true -> false
end
should_print_head_as_charlist and should_print_as_charlist?(tail)
end
end
ExUnit.start()
defmodule HeuristicInferenceTest do
use ExUnit.Case
@input_to_expected_output %{
[] => true,
[0] => false,
[?a] => true,
[0, ?a] => false,
[?a, ?b] => true,
[[?a, ?b], [0, 1]] => false,
[[?a, ?b], [?c, ?d]] => true,
[[[?a], [?b]], [[?c], [?d]]] => true,
[[[?a], [0]], [[?c], [1]]] => false,
["oops"] => false,
[true] => false,
[%{"one" => :two, 3 => "four"}, [2], [72]] => false
}
test "input and expected output pairs (literals)" do
@input_to_expected_output
|> Enum.each(fn {input, expected_output} ->
assert HeuristicInference.should_print_as_charlist?(input) == expected_output
end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment