繁体   English   中英

在Erlang中理解和使用foreach

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM