I’ve been working through the books, answering the questions and building my own v.small projects, it has gotten to a point where I am writing code to get the problem solved so I can progress to the next topics, and even if I expand on the material for extra knowledge, it looks like I might not be fully utilising elixirs conventions.
Example
#all?
def all?([], _), do: true
def all?([h|t], f), do: process_all([h|t], f, f.(h))
def process_all([], _, b) when b == true, do: b
def process_all([h|t], f, b) when b == true, do: process_all(t, f, f.(h))
def process_all(_, _, b) when b == false, do: b
The above seems sort clunky compared to my vague recollection of some examples in prior chapters. What sort of procedure should I follow when choosing a style and also determining the best structure for efficient memory use.
I am currently looking back over previous chapters so that I can see where the disparity lay, but would appreciate some pointers. Below are perhaps a more egregious examples:
#split
def split([], _), do: {[], []}
def split(e, 0), do: {[], e}
def split(e, count) do
prep_c = fn
(_, _, _, count) when count > 0 -> count
(_, [], acc, neg_c) ->
if acc < -neg_c do
0
else
acc + neg_c
end
(f, [_|t], acc, neg_c) -> f.(f, t, acc + 1, neg_c)
end
process_split(e, prep_c.(prep_c, e, 0, count), {[], []})
end
def process_split([], _, {l_i, l_ii}), do: {reverse(l_i, []), reverse(l_ii, [])}
def process_split([h|t], count, {l_ac, list}) when count > 0, do: process_split(t, count - 1, {[h|l_ac], list})
def process_split([h|t], c, {list, l_ac}) when c === 0, do: process_split(t, 0, {list, [h|l_ac]})
##Reverse
def reverse([], acc), do: acc
def reverse([h|t], acc), do: reverse(t, [h|acc])
#Flatten
def flatten([]), do: []
def flatten(list), do: process_flat([], list)
# def flaten(p), do: raise "Argument expected list got #{IO.inspect p}"
def list?([_|_]), do: true
def list?([]), do: true
def list?(_), do: false
def process_flat(list, []), do: reverse(list, [])
def process_flat(list, [h|t]) do
cond do
!list?(h) ->
process_flat([h|list], t)
h !== [] ->
[h_1|t_1] = h
t_2 = [t_1|t]
process_flat(list, [h_1|t_2])
true ->
process_flat(list, t)
end
end