温馨提示×

Erlang列表为空怎么判断

小樊
106
2024-06-14 15:41:23
栏目: 编程语言

在Erlang中,要判断一个列表是否为空,可以使用`is_list/1`和`length/1`函数结合使用,或者直接使用模式匹配

1、使用`is_list/1`和`length/1`函数:

```erlang

is_empty_list([]).

is_empty_list(List) ->

is_list(List) andalso length(List) == 0.

```

这个函数首先检查输入是否为列表,然后检查列表的长度是否为0。如果两个条件都满足,则返回`true`,表示列表为空。

2、使用模式匹配:

```erlang

is_empty_list([]) -> true;

is_empty_list(_) -> false.

```

这个函数使用模式匹配来判断输入是否为空列表。当输入是空列表时,函数返回`true`;否则,返回`false`。

要使用这些函数,只需调用它们并传入要检查的列表作为参数,如下所示:

```erlang

1> empty_list:is_empty_list([]).

true

2> empty_list:is_empty_list([1, 2, 3]).

false

```

在实际编程中,使用模式匹配的方法更为常见,因为它更简洁且易于理解。

0