erlang练习

本文深入探讨了编程中常用的数据结构与算法实现方法,包括列表反转、元素划分、属性提取、IPv4地址解析等核心操作,同时展示了如何通过自定义函数解决实际问题。文章还涉及了日期判断、字符串分割、日期查询历史记录等功能,旨在为开发者提供全面的技术解决方案。
 

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,...]

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值