ramziabbyad1

ramziabbyad1

Pattern matching nested tuples

This is listed as one of the “Hard” problem in 7 languages 7 weeks book. "Represent a tree of sentences as tuples. Traverse the tree, presenting an indented list.

I think I have solved it, but I’m wondering if there is a cleaner way to do this without all the conditionals. Thanks!

Book example:

{“See spot run.”, {“See spot sit”, “See spot run”}} will print

See spot run.
See spot sit
See spot run

And my example:

TreeRecurse.print_tree({"See spot.", {{"See spot sit.", {"Sitting down.", {"Run spot", {"Runnn!"}}}}, "See spot run."}}, "")

will produce the output:

See spot.
See spot sit.
Sitting down.
Run spot
Runnn!
See spot run.

defmodule TreeRecurse do
  def print_tree({leaf}, indent), do: IO.puts "#{indent}#{leaf}"

  def print_tree({root,{lone}},indent) do
    IO.puts "#{indent}#{root}"

    if is_tuple(lone) do
      print_tree(lone, indent <> " ")
    else
      print_tree({lone}, indent <> " ")
    end

  end

  def print_tree({root,{left,right}},indent) do

    IO.puts "#{indent}#{root}"

    if is_tuple(left) do
      print_tree(left, indent <> " ")
    else
      print_tree({left}, indent <> " ")
    end

    if is_tuple(right) do
      print_tree(right, indent <> " ")
    else
      print_tree({right}, indent <> " ")
    end

  end

end

Marked As Solved

zevv

zevv

This is a nice fit for a case with some guards:

  def print_tree2(t, indent) do       
    case t do
      {a, b} when is_binary(a) -> 
        IO.puts "#{indent}#{a}"   
        print_tree2(b, indent <> " ") 
      {a, b} when is_binary(b) ->
        print_tree2(a, indent <> " ") 
        IO.puts "#{indent}#{b}"
      {a} when is_binary(a) ->
        IO.puts "#{indent}#{a}"
    end 
  end

Also Liked

mudasobwa

mudasobwa

Creator of Cure

I always prefer function clauses instead of conditionals (if/2, case/2, cond/1) whenever possible.

defmodule TreeRecurse do
  @indent 2
  
  def print_tree(tree, indent \\ 0, acc \\ []) do
    tree
    |> traverse_tree(indent, acc)
    |> Enum.join("\n")
    |> IO.puts()
  end
  
  defp traverse_tree(leaf, indent, acc) when is_binary(leaf),
    do: [indented(leaf, indent) | acc]
 
  defp traverse_tree({leaf}, indent, acc),
    do: traverse_tree(leaf, indent, acc)

  defp traverse_tree({head, tail}, indent, acc) when is_binary(head) and is_binary(tail),
    do: [indented(head, indent), indented(tail, indent) | acc]
  
  defp traverse_tree({head, tail}, indent, acc) when is_binary(head),
    do: [indented(head, indent) | traverse_tree(tail, indent + 1, acc)] ++ acc
  
  defp traverse_tree({head, tail}, indent, acc) when is_binary(tail),
    do: traverse_tree(head, indent + 1, acc) ++ [indented(tail, indent) | acc]
  
  defp traverse_tree({head, tail}, indent, acc),
    do: traverse_tree(head, indent + 1, acc) ++ traverse_tree(tail, indent + 1, acc) ++ acc
  
  defp indented(input, indent) when is_number(indent),
    do: ' ' |> List.duplicate(indent * @indent) |> to_string() |> Kernel.<>(input) 
end

Where Next?

Popular in Questions Top

Tee
can someone please explain to me how Enum.reduce works with maps
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement