5

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

1 に答える 1

14

構文は、すでに作成した lists:map に似ています。楽しみとリストが必要です。fun は 1 つの引数を取る必要があります。リスト内の各値を渡すと呼び出されます。

lists:foreach(fun(N) ->
                      Encr = encMsg(Message, N),
                      io:format("Key:~p Encrypted: ~p",[N,Encr])
              end, Range).
于 2013-04-19T19:07:40.303 に答える