首页 技术 正文
技术 2022年11月24日
0 收藏 971 点赞 3,607 浏览 1270 个字

erlang 有好几种常用的判断结构语句,如 if、case、guard 等。文章将分别对 if / case /guard 的特点做介绍,以及用例说明

1、if 结构

  1. if
  2. Condition 1 ->
  3. Action 1;
  4. Condition 2 ->
  5. Action 2;
  6. Condition 3 ->
  7. Action 3;
  8. Condition 4 ->
  9. Action 4
  10. end

Erlang是这样工作的:先对Condition 1求值,如值为true,那么将执行Action 1,并跳出该结构。若Condition 1不成功,那么就继续对Condition 2求职,以此类推,直到有条件成功。在if结构中,知道要有一个结果为true,否则Erlang就会抛出一个异常。通常if语句的最后一个条件会是原子true,表示如果没有匹配的条件的话,应该做什么动作。

2、 case 结构

  1. case Condition of
  2. Result 1 ->
  3. Action 1;
  4. Result 2 ->
  5. Action 2;
  6. Result 3 ->
  7. Action 3
  8. end

Erlang是这样工作的:首先,对Condition进行求值,然后将结果依次对Result 1、Result 2等进行匹配,直到找到可以匹配的分支。我们可以把变量_放到最下面的条件层,用来处理没有匹配条件要执行的动作。

3、guard 结构

  1. max(X, Y) when X > Y -> X;
  2. max(X, Y) -> Y.

守卫(guard)是一种用于强化模式匹配功能的结构。如果点第一个子句不匹配,那么erlang会尝试匹配第二个子句。通常把没有任何限定条件的函数放最下面,用来处理没有匹配条件要执行的动作。

下面简单写了一个例子来说明:

    1. -module(compare).
    2. -export([compare/2, compare2/2, compare3/2]).
    3. %% if 语句
    4. compare(A, B) ->
    5. if A > B ->
    6. io:format(“~p > ~p~n”, [A, B]);
    7. A < B ->
    8. io:format(“~p < ~p~n”, [A, B]);
    9. true ->
    10. io:format(“~p = ~p~n”, [A, B])
    11. end.
    12. %% guard 语句
    13. compare2(A, B) when A > B ->
    14. io:format(“~p > ~p~n”, [A, B]);
    15. compare2(A, B) when A < B ->
    16. io:format(“~p < ~p~n”, [A, B]);
    17. compare2(A, B) ->
    18. io:format(“~p = ~p~n”, [A, B]).
    19. %% case 语句
    20. compare3(A, B) ->
    21. case A > B of
    22. true ->
    23. io:format(“~p > ~p~n”, [A, B]);
    24. _ ->
    25. case A < B of
    26. true ->
    27. io:format(“~p < ~p~n”, [A, B]);
    28. _ ->
    29. io:format(“~p = ~p~n”, [A, B])
    30. end
    31. end.
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,957
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,480
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,327
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,110
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,742
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,776