i want write function replace specific atom given atom in input list. want using pattern matching , not using conditional statements. idea?
and want write function return unique atoms in expression. e.g.
input:
[a, b, c, a, b]
output:
c
input:
[b, b, b, r, t, y, y]
output:
[t, r]
assuming want replace instances , keep order of list (works terms):
replace(old, new, list) -> replace(old, new, list, []). replace(_old, _new, [], acc) -> lists:reverse(acc); replace(old, new, [old|list], acc) -> replace(old, new, list, [new|acc]); replace(old, new, [other|list], acc) -> replace(old, new, list, [other|acc]).
for unique elements filter, need keep state of elements have looked @ already.
it awkward implement such function using pattern matching in function headers , not gain (performance) it. awkwardness come having loop through both list in question , list(s) keeping state of parsed elements. loose lot of readability.
i recommend going simpler (works terms, not atoms):
unique(list) -> unique(list, []). unique([], counts) -> lists:foldl(fun({e, 1}, acc) -> [e|acc]; (_, acc) -> acc end, [], counts); unique([e|list], counts) -> unique(list, count(e, counts). count(e, []) -> [{e, 1}]; count(e, [{e, n}|rest]) -> [{e, n + 1}|rest]; count(e, [{x, n}|rest]) -> [{x, n}|count(e, rest)].
Comments
Post a Comment