Erlang几种判断语句:if、case等

本文介绍了Erlang中的三种判断结构:if、case及guard的使用方法与特点。通过实例详细展示了这些结构如何帮助开发者实现逻辑判断和模式匹配。

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

Erlang有几种常用的判断结构语句,如if、case等。本篇侧重介绍其特点,以及用例说明

1、if 结构

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

2、 case 结构

case Condition of 
     Result 1 ->
           Action 1;      
     Result 2 ->
           Action 2;
     Result 3 ->
           Action 3
end

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

3、guard 结构

max(X, Y) when X > Y -> X;
max(X, Y) -> Y.
守卫(guard)是一种用于强化模式匹配功能的结构。如果点第一个子句不匹配,那么erlang会尝试匹配第二个子句。


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

-module(compare).

-export([compare/2, compare2/2, compare3/2]).

%% if 语句
compare(A, B) ->
	if A > B ->
			io:format("~p > ~p~n", [A, B]);
	   A < B ->
			io:format("~p < ~p~n", [A, B]);
	   true ->
			io:format("~p = ~p~n", [A, B])
	end.

%% guard 语句
compare2(A, B) when A > B ->
	io:format("~p > ~p~n", [A, B]);
compare2(A, B) when A < B ->
	io:format("~p < ~p~n", [A, B]);
compare2(A, B) ->
	io:format("~p = ~p~n", [A, B]).

%% case 语句
compare3(A, B) ->
	case A > B of
		true ->
			io:format("~p > ~p~n", [A, B]);
		_ ->
			case A < B of
				true ->
					io:format("~p < ~p~n", [A, B]);
				_ ->
					io:format("~p = ~p~n", [A, B])
			end
	end.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值