Last active
January 9, 2018 10:31
-
-
Save unixc3t/88e699f399c4275b7fea59fec49a19e9 to your computer and use it in GitHub Desktop.
erlang尾递归练习(recursion)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%%计算链表长度尾递归实现 | |
lez(N) -> lez(N, 0). | |
lez([], Acc) -> Acc; | |
lez([_ | T], Acc) -> lez(T, Acc + 1). | |
%% 将某个元素重复n次返回一个链表 | |
dulicate(0,_) ->[]; | |
dulicate(N,DATA) -> [X | dulicate(N-1,X)]. | |
%% 尾递归版本 | |
my_duplicate(ARG,DATA) -> my_duplicate_a(ARG,DATA,[]). | |
my_duplicate_a(0,_,RESULT) -> RESULT; | |
my_duplicate_a(ARG,DATA,RESULT)-> my_duplicate_a(ARG-1,DATA,[DATA | RESULT]). | |
%%翻转一个链表 | |
zreverse_list([]) -> []; | |
zreverse_list([X|REST]) -> [zreverse_list(REST)|[X]] | |
%%尾递归版本 | |
tail_reverse_list(N)->reverse_list(N,[]). | |
reverse_list([],ACC) -> ACC; | |
reverse_list([X|REST],ACC) -> reverse_list(REST,[X|ACC]). | |
%%获取一个链表的前N项,如果N大于链表长度,返回整个链表 | |
sublist([], _) -> []; | |
sublist(X, N) when N < 0 -> []; | |
sublist(X, N) when N =:= 0 -> []; | |
sublist([X | REST], N) -> [X | sublist(REST, N - 1)]. | |
%%尾递归版 | |
rsublist(N, X) -> zsublist(N, X, []). | |
zsublist([], _, ACC) -> ACC; | |
zsublist(X, N, ACC) when N < 0 -> ACC; | |
zsublist(X, N, ACC) when N =:= 0 -> ACC; | |
zsublist([X | REST], N, ACC) -> zsublist(REST, N - 1, ACC++[X]). | |
%%合并两个链表,两个链表每取出一项组成元祖 最后返回一个链表 eg: [1,2],[a,b] => [{1,a},{2,b}] | |
zzip([], _) -> []; | |
zzip(_, []) -> []; | |
zzip([], []) -> []; | |
zzip([X | RE], [Y | ST]) -> [{X, Y} | zzip(RE, ST)]. | |
%%尾递归版本 | |
tail_zzip(X, Y) -> rzzip(X, Y, []). | |
rzzip([], _, ACC) -> ACC; | |
rzzip(_, [], ACC) -> ACC; | |
rzzip([], [], ACC) -> ACC; | |
rzzip([X | RE], [Y | ST], ACC) -> rzzip(RE, ST, ACC ++ [{X, Y}]). | |
%%传递函数作为参数,将列表参数添加或者减少 | |
r_laddone(N, Fn) -> laddone(N, [], Fn). | |
laddone([], ASS, Fn) -> ASS; | |
laddone([H | RE], ASS, Fn) -> laddone(RE, ASS ++ [Fn(H)],Fn). | |
incr(X) -> X + 1. | |
decr(X) -> X - 1. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment