Erlang - Guards

Erlang - Guards 首页 / Erlang入门教程 / Erlang - Guards

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 语句。

If 语句

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 语句

保护还可以用于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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Linux实战技能100讲 -〔尹会生〕

深入浅出云计算 -〔何恺铎〕

爱上跑步 -〔钱亮〕

Python自动化办公实战课 -〔尹会生〕

零基础入门Spark -〔吴磊〕

手把手带你搭建秒杀系统 -〔佘志东〕

React Native 新架构实战课 -〔蒋宏伟〕

说透元宇宙 -〔方军〕

超级访谈:对话毕玄 -〔毕玄〕

好记忆不如烂笔头。留下您的足迹吧 :)