簡體   English   中英

如何在 Erlang 中使用整個列表函數參數

[英]How to use whole list function argument in Erlang

我可以理解我在文檔中閱讀的大部分[H|T]示例。 我通常的意思是我想使用列表的HT部分。 如果我想改用整個列表怎么辦。 示例代碼:

-module(module_variable).
-export([main/0, list_suffix/1]).

variable() -> [1, 2, 3, 4, 5].

list_suffix([_H|T]) ->
        lists:suffix(variable, T).

main() ->
        io:fwrite("~p~n", [list_suffix([4, 5])]).

我得到的錯誤是:

6> module_variable:list_suffix([1,[4, 5]]).
** exception error: bad argument
     in function  length/1
        called as length(variable)
     in call from lists:suffix/2 (lists.erl, line 205)

幫助表示贊賞。

您可以使用列表前面的多個值。 您不能在中間跳過任意數量的值。 由於在您的代碼中,您不知道要提前匹配頭部的多少元素,因此模式匹配無法為您做到這一點。

一些例子:

設置:

1> A = [1, 2, 3, 4, 5].
[1,2,3,4,5]

匹配列表的前 2 個元素

2> [1, 2 | _ ] = A.
[1,2,3,4,5]
% Can pattern match to extract values
3> [B, C | _ ] = A.    
[1,2,3,4,5]
4> B.
1
5> C.
2

可以匹配一些常量值並分配

6> [1, 2, D | _ ] = A.
[1,2,3,4,5]

可以匹配整個列表

7> [1, 2, 3, 4, 5] = A. 
[1,2,3,4,5]
% Can't skip over elements in the middle
8> [1, 2| [4, 5]] = A. 
** exception error: no match of right hand side value [1,2,3,4,5]
% This works, though not useful most of the time:
9> [1, 2, 3 | [4, 5]] = A.
[1,2,3,4,5]
% Can assign every element
10> [B, C, D, E, F] = A.
[1,2,3,4,5]
11> E.
4
12> F.
5
% If you don't use a pipe, the length has to match exactly
13> [B, C, D, E] = A.   
** exception error: no match of right hand side value [1,2,3,4,5]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM