Guard语句的一般语法如下-
function(parameter) when condition ->
function(parameter) - 函数声明。
parameter - 函数参数。
condition - 判断条件。
when - 指定条件时。
让我们看一下如何使用guard防护的简单示例-
-module(helloLearnfk). -export([display/1,start/0]). display(N) when N > 10 -> io:fwrite("greater then 10"); display(N) when N < 10 -> io:fwrite("Less than 10"). start() -> display(11).
上面程序的输出如下:
greater than 10
guard条件也可以用于 if 和 case 语句。
guard还可以用于if语句,让我们看看如何实现这一目标。
-module(helloLearnfk). -export([start/0]). start() -> N=9, if N > 10 -> io:fwrite("N is greater than 10"); true -> io:fwrite("N is less than 10") end.
上面程序的输出如下:
N is less than 10
保护还可以用于case语句,让我们看看如何实现这一目标。
-module(helloLearnfk). -export([start/0]). start() -> A=9, case A of {A} when A>10 -> io:fwrite("The value of A is greater than 10"); _ -> io:fwrite("The value of A is less than 10") end.
上面程序的输出如下:
The value of A is less than 10
也可以为一个函数指定多个guard防护条件。
function(parameter) when condition1 , condition1 , .. conditionN ->
function(parameter) - 函数声明。
parameter - 函数参数。
condition1,condition1,.. conditionN - 这些是应用于函数的条件。
when - 指定条件时使用。
让我们看一下简单示例-
-module(helloLearnfk). -export([display/1,start/0]). display(N) when N > 10 , is_integer(N) -> io:fwrite("greater then 10"); display(N) when N < 10 -> io:fwrite("Less than 10"). start() -> display(11).
上面程序的输出如下:
Greater than 10
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)