Erlang入门

本文展示了Erlang编程中的关键概念,包括定义记录类型`person`,函数`hello`的参数和返回类型注解,以及递归函数`fac`和`total_sum`的实现。此外,还涵盖了如何操作映射(map),如创建和访问map中的值。
摘要由CSDN通过智能技术生成
%%%-------------------------------------------------------------------
%%% @author sunxu
%%% @copyright (C) 2023, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 16. 2月 2023 22:16
%%%-------------------------------------------------------------------
-module(test).
-author("sunxu").

%% API 设置导出的函数
-export([hello_world/0]).


%%%%%%%%%%%%%%% 第一部分 record type spec %%%%%%%%%%%%%%%
% 结构体 person
-record(person, {
  name = <<>> :: string(),
  age = 18 :: pos_integer(),
  sex = <<>> :: string(),
  height :: pos_integer()
}).

% 定义类型
-type person() :: #person{}.

% 设置函数hello入参和返回类型
-spec hello(person(),integer()) -> person().

% Height变量用来提取Sun中的height字段的值
hello(#person{height = Height} = Sun,Age)->
  Jing = Sun#person{name = "jing", age = Age, height = Height-13, sex = "woman"},
  Sex = Sun#person.sex,
  io:format("Person  is : ~p ~n", [ Sex ]),
  io:format("Person  is : ~p ~n", [ Sun ]),
  io:format("Person  is : ~p ~n", [ Jing ]),
  Jing.

%%%%%%%%%%%%%%% 第一部分 record type spec %%%%%%%%%%%%%%%



%%%%%%%%%%%%%%% 第二部分 函数递归 %%%%%%%%%%%%%%%

% 阶乘
fac(1) ->
  1;

fac(N) ->
  N*fac(N-1).

% 求和, | 符号用来切分列表
total_sum([]) ->
  0;

total_sum([First|Rest]) ->
  First+total_sum(Rest).

%%%%%%%%%%%%%%% 第二部分 函数递归 %%%%%%%%%%%%%%%



%%%%%%%%%%%%%%% 第三部分 map %%%%%%%%%%%%%%%
getmap(Username,Password) ->
  #{
    name => Username,
    pass => Password
  }.

% 使用 := 匹配map中的name对应的值,并将其赋值到User变量中
alpha(#{name := User}) ->
  io:format("Username is: ~p ~n",[User]).
%%%%%%%%%%%%%%% 第三部分 map %%%%%%%%%%%%%%%



hello_world() ->
  Sun = #person{name = "sunxu",height = 178,sex = "man"},
  hello(Sun,18),

  io:format("Factorial result: ~p ~n",[fac(7)]),

  io:format("total sum is: ~p ~n",[total_sum([1,2,3,4,5])]),

  alpha(getmap("sunxu","sunxu")).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值