[英]Understanding and using foreach in Erlang
我有一個任務,用7種語言完成凱撒密碼。 我正在努力完成Erlang目前。 我以前接觸過函數式語言,所以我一般都明白我需要做什么。 我特別難以理解Erlang中foreach函數的用法。 我知道當你對副作用感興趣時會使用它,所以我很確定這是做我想要的“正確”方式。 我讀過這個答案 ,並用Erlang語言參考在foreach的定義在這里 。 但是,我仍然有點困惑,無法正確使用語法。
-module(caesar).
-export([main/2]).
enc(Char,Key) when (Char >= $A) and (Char =< $Z) or
(Char >= $a) and (Char =< $z) ->
Offset = $A + Char band 32, N = Char - Offset,
Offset + (N + Key) rem 26;
enc(Char, _Key) -> Char.
encMsg(Msg, Key) ->
lists:map(fun(Char) -> enc(Char, Key) end, Msg).
main(Message, Key) ->
Encode = (Key),
Decode = (-Key),
Range = lists:seq(1,26),
io:format("Message: : ~s~n", [Message]),
Encrypted = encMsg(Message, Encode),
Decrypted = encMsg(Encrypted, Decode),
io:format("Encrypted: ~s~n", [Encrypted]),
io:format("Decrypted: ~s~n", [Decrypted]),
io:format("Solution: ").
%% Foreach belongs here, should execute Encrypted = encMsg(Message, N) where
%% N is the value in Range for each value in the list, and then print Encrypted.
語法類似於list:您已編寫的map。 它需要一個有趣的列表。 樂趣應該是一個論點。 它將被調用傳遞列表中的每個值。
lists:foreach(fun(N) ->
Encr = encMsg(Message, N),
io:format("Key:~p Encrypted: ~p",[N,Encr])
end, Range).
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.