I have an assignment to complete a caesar cypher in 7 languages. I'm working on completing it Erlang currently. 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. 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. 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. 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With