简体   繁体   English

在Erlang中理解和使用foreach

[英]Understanding and using foreach in Erlang

I have an assignment to complete a caesar cypher in 7 languages. 我有一个任务,用7种语言完成凯撒密码。 I'm working on completing it Erlang currently. 我正在努力完成Erlang目前。 I've been exposed to functional languages before so I generally understand what I need to do. 我以前接触过函数式语言,所以我一般都明白我需要做什么。 I'm specifically having trouble understanding the usage of the foreach function in Erlang. 我特别难以理解Erlang中foreach函数的用法。 I know it's used when you are interested in a side effect, so I'm pretty sure it's the "right" way to do what I want. 我知道当你对副作用感兴趣时会使用它,所以我很确定这是做我想要的“正确”方式。 I've read this answer and the definition of foreach in the Erlang language reference here . 我读过这个答案 ,并用Erlang语言参考在foreach的定义在这里 However, I'm still a little confused and having trouble getting the syntax right. 但是,我仍然有点困惑,无法正确使用语法。

-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.

The syntax is similar to lists:map that you have already written. 语法类似于list:您已编写的map。 It takes a fun and the list. 它需要一个有趣的列表。 The fun should take one argument. 乐趣应该是一个论点。 It will be called passing each value in the list. 它将被调用传递列表中的每个值。

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