Erlang day1

1. Erlang21下载

http://www.erlang.org/downloads

2. IDEA安装Erlang环境

windows:https://blog.csdn.net/wu4517519/article/details/80148150
linux:https://www.erlang-solutions.com/resources/download.html

3. 相关命令

windows进入linux :wsl
进入erlang shell :erl

4. Hello world

hello.erl
-module(hello).
-export([start/0]).
start() ->
  io:format("Hello world~n").
1> c(hello). %编译erl文件
2> hello:start().
3> halt(). % 推出

5. 文件服务器进程

afile_server.erl
-module(afile_server).
-export([start/1, loop/1]).

start(Dir) -> spawn(afile_server, loop, [Dir]).  %返回进程号<0.47.0>

loop(Dir) ->
  receive
    {Client, list_dir} ->
      Client ! {self(), file:list_dir(Dir)};  %返回文件列表
    {Client, {get_file, File}} ->
      Full = filename:join(Dir, File),
      Client ! {self(), file:read_file(Full)}  %返回文件内容
  end,
  loop(Dir).
afile_client.erl
-module(afile_client).
-export([ls/1, get_file/2]).
ls(Server) ->
  Server ! {self(), list_dir},   % 向服务端发送消息, self()告知服务端回复自己
  receive
    {Server, FileList} ->
      FileList
  end.
  
get_file(Server, File) ->
  Server ! {self(), {get_file, File}}, 
  receive
    {Server, Content} ->
      Content
  end.
1> c(afile_server).
2> c(afile_client).
3> FileServer = afile_server:start(".").  %开启一个服务端进程
4> afile_client:get_file(FileServer,"afile_server.erl").

6. Erlang shell

6.1 浮点数

N div M 是让N除以M后舍去余数。 N rem M是N除以M剩下的余数

1> 5 div 3.
1
2> 5 rem 3.
2

6.2 元组

1> Person = {person,{name, joe, armstrong}, {footsize,42}}.
2> {_,{_,Who,_},_} = Person.
3> Who.
joe

6.3 列表

1> ThingsToBuy = [{apples, 10}, {pears, 6}].
2> ThingsToBuy1 = [{oranges, 4},{newspaper,1} | ThingsToBuy]. %合并
 [{oranges, 4},{newspaper,1} ,{apples, 10}, {pears, 6}]
3> [Buy1|ThingsToBuy2] = ThingsToBuy1. % 绑定Buy1 = {oranges,4} 
4> [Buy2,Buy3|ThingsToBuy3] = ThingsToBuy2.  % 绑定Buy2 = {newspaper,1}, 绑定Buy3 = {apples, 10}

7. 模块

shop.erl
-module(shop).
-export([cost/1]).
%各商品价格
cost(oranges) -> 5;
cost(newspaper) -> 8;
cost(apples) -> 2;
cost(pears) -> 9;
cost(milk) -> 7.
shop1.erl
-module(shop1).
-export([total/1]).

total([{What, N}|T]) ->
  shop:cost(What) * N + total(T);  %递归计算总价
total([]) -> 0.
1> c(shop).
{ok,shop}
2> c(shop1).
{ok,shop1}
3> Buy = [{apples,10},{oranges,3},{pears, 9}].
[{apples,10},{oranges,3},{pears,9}]
4> shop1:total(Buy).
116

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值