簡體   English   中英

實施列表:map 使用 case 子句代替 Erlang 中的 function 子句

[英]Implement a lists:map using case clauses instead of function clauses in Erlang

誰能告訴我這是什么意思? 我是新手,我的朋友推薦我在這個網站上發帖。 順便說一句,我是 Erlang 的新手。

如果可能的話,我想在編輯器中編寫代碼,但我什至不理解任何示例輸入/輸出的問題以及它如何工作的解釋。 謝謝

在我看來,這個問題是指lists:map/2的實現,一個 function 將相同的 function (作為參數接收)應用於列表的所有元素並返回結果列表。

換句話說,這個 function

您可以查看OTP Github 存儲庫以了解 function 是如何實現的:

map(F, List) when is_function(F, 1) ->
    case List of
        [Hd | Tail] -> [F(Hd) | map_1(F, Tail)];
        [] -> []
    end.

map_1(F, [Hd | Tail]) ->
    [F(Hd) | map_1(F, Tail)];
map_1(_F, []) ->
    [].

或者您可以設想一個更簡單的實現,如……

map(F, []) -> [];
map(F, [H|T]) -> [F(H) | map(F, T)].

它們(對於 OTP 版本,我指的是map_1/2 )都在 function 子句頭中使用模式匹配來區分基本情況和 function 的遞歸步驟。

您收到的請求是使用帶有case子句的單個 function 子句而不是上面看到的兩個 function 子句來實現相同的算法。

任何示例輸入/輸出及其工作原理的解釋都可以

在 Brujo Benavides 的回答中鏈接的文檔中,您可以看到:

從 As 到 Bs 獲取 function 和 As 列表,並通過將 function 應用於列表中的每個元素來生成 Bs 列表。 這個function是用來獲取返回值的。

所以F是一個 function(單個參數),例如fun(X) -> X*2 end 請參閱https://www.erlang.org/doc/programming_examples/funs.html#syntax-of-funshttps://www.erlang.org/doc/reference_manual/expressions.html#funs以了解fun的表達式。 List1是 function F可以處理的值列表(在本例中為數字),例如[1,2,3] 然后list:map(fun(X) -> X*2 end, [1,2,3])在列表[1,2,3]的每個元素上調用fun(X) -> X*2 end並返回返回值列表[2,4,6] 您的 function 應該在這些 arguments 上給出相同的結果。

下面是一個簡單的例子,展示了如何使用 function 子句,然后是 case 語句來做同樣的事情。 將以下代碼放在某個目錄下名為a.erl的文件中:

-module(a).
-export([show_stuff/1, show_it/1]).

show_stuff(1) ->
    io:format("The argument was 1~n");
show_stuff(2) ->
    io:format("The argument was 2~n");
show_stuff(_)->
    io:format("The argument was something other than 1 or 2~n").

show_it(X) ->
    case X of
        1 -> io:format("The argument was 1~n");
        2 -> io:format("The argument was 2~n");
        _ -> io:format("The argument was something other than 1 or 2~n")
    end.

請注意文件名、 a.erl和模塊指令:

-module(a).

必須匹配。 因此,如果您將文件命名為homework1.erl ,那么文件中的模塊指令必須是:

-module(homework1).

為了節省大量的輸入,最好使用非常短的模塊名稱(如下所示)。

在終端 window 中,將目錄切換到包含a.erl的目錄:

 ~$ cd erlang_programs/

然后啟動 erlang shell:

 ~/erlang_programs$ erl
Erlang/OTP 24 [erts-12.0.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1]

Eshell V12.0.2  (abort with ^G)

接下來,執行以下語句:

1> c(a).   <--- Compiles the code in your file 
{ok,a}     <--- Or, you may get errors which must be corrected, then try recompiling.

2> a:show_stuff(1).
The argument was 1
ok

3> a:show_stuff(4).
The argument was something other than 1 or 2
ok

4> a:show_it(1).
The argument was 1
ok

5> a:show_it(4).
The argument was something other than 1 or 2
ok

6> 

請注意調用文件/模塊中定義的 function 的語法:

 module_name:function_name(arg1, arg2, ... argn).

暫無
暫無

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

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