erlang 购物

本文介绍了一个使用Erlang实现购物计算的例子,通过递归处理商品列表达到总价计算。代码示例展示了如何处理包含不同商品数量的列表,并逐步解析递归过程。尽管Erlang的语法简洁,但递归逻辑可能对初学者来说较难理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

shop.erl
%% Author: Administrator
%% Created: 2012-8-23
%% Description: TODO: Add description to shop
-module(shop).
%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([cost/1]).

%%
%% API Functions
%%
cost(oranges)
  ->5;
cost(newspaper)
  ->8;
cost(apples)
  ->2;
cost(pears)
  ->9;
cost(milk)
  ->7.


%%
%% Local Functions
%%


shop1.erl

%% Author: Administrator
%% Created: 2012-8-23
%% Description: TODO: Add description to shop1
-module(shop1).

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([total/1]).

%%
%% API Functions
%%
total([{What,N}|T])
  ->shop:cost(What)*N+total(T);
total([])
  ->0.


%%
%% Local Functions
%%


cd("/mnt/web/source_erlang/demo1/src").
c(shop).
c(shop1).
Buys=[{oranges,4},{newspaper,1},{apples,10},{pears,6},{milk,3}].
shop1:total(Buys). 

这点代码很有意思,递归是必须的,主要是在shop:cost(What)*N+total(T)

T是列表的后面的数据,依次递归下去,直至为空,当为空时变成匹配total([])方法

执行方式应该是

oranges*4+{newspaper,1},{apples,10},{pears,6},{milk,3}=40+{newspaper,1},{apples,10},{pears,6},{milk,3}

40+newspaper*1=40+8+{apples,10},{pears,6},{milk,3}

一直下去,最后变成了

40+8+2*10+9*6+7*3+total([]) //total([])=0


ps:尼玛,这也太精简了,python哪能和这语言相比,不过就是真TMD难懂,递归精简,我擦了.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值