2013-04-19 11 views
5

私は7ヶ国語でシーザーサイファーを完成するという課題があります。私は現在Erlangを完了するために取り組んでいます。私は関数型言語に慣れてきたので、私は一般的に何をする必要があるのか​​理解しています。私は具体的にErlangのforeach関数の使い方を理解するのに困っています。あなたが副作用に興味を持っているときに使用されていることは分かっています。だから私はそれが私が望むことを "正しい"方法であると確信しています。私はthis answerとErlang言語リファレンスhereの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. 

答えて

10

構文は、すでに作成したlists:mapと似ています。それは楽しいとリストを取る。楽しさは1つの議論を取るべきです。これは、リスト内の各値を渡すことによって呼び出されます。

lists:foreach(fun(N) -> 
         Encr = encMsg(Message, N), 
         io:format("Key:~p Encrypted: ~p",[N,Encr]) 
       end, Range). 
+0

完璧、私のためにそれをクリアしました。ありがとう! – NickAbbey

関連する問題