sodapopcan

sodapopcan OP

In complex cases for sure—I did a little parser thing once and didn’t use do_ at all, but I honestly don’t write a lot of recursive functions. I mostly do simple cases and (and I’m entering into mega bikeshed territory here) I hate when things have names for the sake of having names… if that makes sense? Like when I see _other -> true in a catch-all or the like. I name my _ vars 99% of the time but case like that I’m like, “Duh, I know it’s ‘other’!”

I dunno, I’m procrastinating on a project right now :sweat_smile:

1
Post #11
adamu

adamu

Hopefully this is at least par for the course :in_hole:. @Ninigi I’m interested in what you’d use instead of do_ here.

defmodule Example do
  def segment_path(path) do
    path |> String.split("/", trim: true) |> do_segment_path("")
  end

  defp do_segment_path([], _path), do: []

  defp do_segment_path([current | rest], path) do
    new_path = "#{path}/#{current}"
    [{current, new_path} | do_segment_path(rest, new_path)]
  end
end

Running:

iex(1)> Example.segment_path("path/to/segment")
[{"path", "/path"}, {"to", "/path/to"}, {"segment", "/path/to/segment"}]
3
Post #12
Sebb

Sebb 

import Enum

def bread(p), do: p |> String.split("/") |> split(-1) |> bread_()

defp bread_({[], _}), do: []
defp bread_({p, [s]}), do: [{s, join(p ++ [s], "/")}] ++ (p |> split(-1) |> bread_())

bread("/path/to/segment") #=>
 [{"segment", "/path/to/segment"}, {"to", "/path/to"}, {"path", "/path"}]

this is inefficient, but easy to follow and short. I opt for easy here because this will never be time critical.
“Fast-readability” is also a kind of fast code.

0
Post #13
cloudytoday

cloudytoday

With a for comprehension:

iex(109)> sp = fn path ->
...(109)>   split = String.split(path, "/")
...(109)>   for el <- split do
...(109)>     path = Enum.take_while(split, & &1 != el) ++ [el]
...(109)>     {el, Enum.join(path, "/")}
...(109)>   end
...(109)> end
#Function<42.3316493/1 in :erl_eval.expr/6>
iex(110)> sp.("path/to/some/segment")
[
  {"path", "path"},
  {"to", "path/to"},
  {"some", "path/to/some"},
  {"segment", "path/to/some/segment"}
]
2
Post #14
GPrimola

GPrimola

I loved how simple and straightforward this looks!

1
Post #15
sodapopcan

sodapopcan OP

lol, thanks for necroing this thread as made me realize I never marked a solution :sweat_smile:

0
Post #16
smathy

smathy

Late to the party here, but I’d use the Path helpers:

  def segment_path(path) when is_binary(path) do
    do_segment_path(path)
    |> Enum.reverse()
  end

  defp do_segment_path("/"), do: []

  defp do_segment_path(path) do
    [ { Path.basename(path), path } | do_segment_path(Path.dirname(path)) ]
  end
3
Post #17
sodapopcan

sodapopcan OP

I mean, ya, that one certainly works well :sweat_smile:

0
Post #18
— All posts loaded —