small medium large xlarge

Photo may 19, 5 22 08_pragsmall
28 Jun 2013, 00:16
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 Thomas (396 posts)
In general, you probably want to avoid ++. It is considerably less efficient that building a list using [ ]
12 Nov 2014, 06:32
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)

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