Is ++ operator more expensive than | operator in Erlang? -
i reading learn erlang , came upon example in recursion chapter.
tail_sublist(_, 0, sublist) -> sublist; tail_sublist([], _, sublist) -> sublist; tail_sublist([h|t], n, sublist) when n > 0 -> tail_sublist(t, n-1, [h|sublist]).
as author goes on explain there fatal flaw in our code. being sub lists hence produced reverse , have re-reverse them correct output. in contrast, did use ++
operator avoid reversing list later.
sublist_tail([],_,acc) -> acc; sublist_tail(_,0,acc) -> acc; sublist_tail([h|t],n,acc) -> sublist_tail(t,n-1,acc++[h]).
my question is, is ++
operator more expensive |
operator? , if is, would solution (using ++
operator) still slow compared author's solution (including reversing list correct output)?
is ++ operator more expensive | operator?
that depends. if use correctly, no. ++
dangerous when have big left-hand-side operand.
each time "++
"-operator invoked on left-hand list (like: list1 ++ list2
), creating new list, copy of left-hand operand (list1
). each copy operation has runtime, dependent on length of list1
(which keeps growing iterations).
so, if prepend values 'head first', don't have perform copy-operation on whole list in each step. means, accumulation ++
@ head of list wouldn't bad either, since "h"-value copied once in each iteration:
sublist_tail([h|t],n,acc) -> sublist_tail(t,n-1,[h]++acc).
but if accumulating head-first (and have reverse later anyhow), can cons-operator (|
)
sublist_tail([h|t],n,acc) -> sublist_tail(t,n-1,[h|acc]).
this 'proper' way, since (please correct me if wrong) ++
syntactic sugar , implemented internally cons-operator (|
).
Comments
Post a Comment