erlang - Reverse a list using recursion -
i'm doing examples book on erlang. here task: write reverse function without using bifs.
here's did:
reverse([h | t]) -> [reverse(t) | [h]]; reverse([]) -> [].
here's function returns:
(emacs@localhost)3> examples:reverse([1, 2, 3]). [[[[],3],2],1]
i can't understand how can make return flattened list [3, 2, 1]
. possible @ all?
in syntax [h|t], h element , t list (at least proplist), in code [reverse(t) | [h]]
creates list first element result of reverse(t)
, , tail single element list [h]
.
if want achieve function way, should use syntax proposed fenollp.
if want write efficient code, should avoid make multiple intermediate copy of partial results, , avoid non tail recursive calls (in order limit size of call stack:
reverse(l) -> reverse(l,[]). % use accumulator create tail recursive function reverse([],r) -> r; reverse([h|t],r) -> reverse(t,[h|r]). % [h|r] can evaluated before recursively calling reverse % called tail recursive function % in addition, construction of [h|t] % not require make copy of t
Comments
Post a Comment