4. [1,2,3,...,5] ->[5,...,3,2,1] (not use lists:reverse)
reverse(L) -> reverse(L, []).
reverse([], Acc) -> Acc;
reverse([H|T], Acc) -> reverse(T, [H|Acc]).
方法二:
f([H|T]) ->
f(T) ++ [H];
f([]) -> [].
5. [1,a,"s","d",3,b]->[1,3],[a,b],["s","d"]
split(L) ->
split(L, [], [], []).
split([H|T], I, A, S) ->
if
is_integer(H) -> split(T, [H|I], A, S);
is_atom(H) -> split(T, I, [H|A], S);
is_list(H) -> split(T, I, A, [H|S])
end;
split([], I, A, S) -> [lists:reverse(I), lists:reverse(A), lists:reverse(S)].
6. L=[{Name,Value},...]
e.g.
L=[{high, 4},{width,6},{weight,16}]
4=fun(L,high)
6=fun(L,width)
undefined=fun(L,high1)
What is fun/2? (not use lists:xxxx )
myfun([], _) ->
undefined;
myfun([{Target, Value}|_], Target) ->
Value;
myfun([_ | T], Target) ->
myfun(T, Target).
test1() ->
L =[{high, 4},{width,6},{weight,16}],
[myfun(L, high), myfun(L, width), myfun(L, weight), myfun(L, high1)].
7. decode IPv4 adddress
str_to_ipv4("150.236.11.1")->{150,236,11,1}
str_to_ipv4("150.236.1234.1")->{error, bad_format}
check_ipv4_addr_value(S) ->
{X, _} = string:to_integer(S),
case (X >= 0) and (X =< 255) of
true -> X;
_ ->
throw(bad_format)
end.
str_to_ipv4(Str) ->
L = string:tokens(Str, "."),
case (length(L) =:= 4) of
true ->
str_to_ipv4(L, []);
_ ->
{error, bad_format}
end.
str_to_ipv4([], R) ->
list_to_tuple(lists:reverse(R));
str_to_ipv4([H|T], R) ->
try check_ipv4_addr_value(H) of
X ->
str_to_ipv4(T, [X|R])
catch
throw:bad_format ->
{error, bad_format}
end.
test() ->
[str_to_ipv4("150.236.11.1"),
str_to_ipv4("150.236.1234.1"),
str_to_ipv4("1.1.1.1.1")].
8. split words.
split("Ah, I have a dream!") ->["Ah","I","have","a","dream"].
9. check the year is leap-year or not.
Please google the leap-year rule.
is_leap_year(Int): true|false
10. leap year server. leap_svr.erl
1) allow customer to query the year is leap year or not.
query(Int): true|false
2) record the query history.
Include the year number be queried.
e.g. 1998,2002,2340,12453.
3) allow cusotmer to query the query hisoty.
history(): [1998,2002,...]
本文深入探讨了编程中常用的数据结构与算法实现方法,包括列表反转、元素划分、属性提取、IPv4地址解析等核心操作,同时展示了如何通过自定义函数解决实际问题。文章还涉及了日期判断、字符串分割、日期查询历史记录等功能,旨在为开发者提供全面的技术解决方案。
753

被折叠的 条评论
为什么被折叠?



