28 Jun 2013, 00:16
Photo may 19, 5 22 08_pragsmall

James Martin (1 post)

My solution to the @flatten(list)@ exercise in section 7.6 doesn’t use reverse, as the hint suggests. Here’s my version:

def flatten([]), do: []
def flatten([head|tail]), do: flatten(head) ++ flatten(tail)
def flatten(head), do: [head]

I’m curious what the solution looks like if you do use reverse to solve this problem. Anybody care to share their solution?

28 Jun 2013, 18:45
Dave_gnome_head_isolated_pragsmall

Dave Thomas (344 posts)

In general, you probably want to avoid ++. It is considerably less efficient that building a list using [ ]
12 Nov 2014, 06:32
5971263675_f01d667f5b_z_pragsmall

Stuart Blair (3 posts)

So after wondering how you’d need to use reverse to solve the problem, I too came here.

My solution is as follows, but if anyone has solved it using reverse I’d love to see it.

def flatten([]), do: []

def flatten([head | tail]) when not is_list(head) do
  [head] ++ flatten(tail)
end

def flatten([head | tail]) when is_list(head) do
  flatten(head) ++ flatten(tail)
end
  You must be logged in to comment