我有一项任务,用7种语言完成凯撒密码。我正在努力完成Erlang目前。我以前接触过函数式语言,所以我一般都明白我需要做什么。我特别难以理解Erlang中foreach函数的用法。我知道当你对副作用感兴趣时会使用它,所以我很确定这是做我想要的“正确”方式。我在Erlang语言参考this answer中阅读了here和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.
答案 0 :(得分:12)
语法类似于list:您已编写的map。它需要一个有趣的列表。乐趣应该是一个论点。它将被称为传递列表中的每个值。
lists:foreach(fun(N) ->
Encr = encMsg(Message, N),
io:format("Key:~p Encrypted: ~p",[N,Encr])
end, Range).