در این مثال دو رشته از ورودی دریافت میشود و سپس بررسی میشود که آیا آن دو آناگرام هستند یا نه. دو رشته را در حالی آناگرام میگویند که از کارکترهای یکسانی تشکیل شده باشند. برای نمونه note و tone آناگرام هستند. برای حل این مثال از نوع map استفاده کردم که در آن هر کارکتر یک کلید و تعداد تکرارش مقدار آن میباشد.
%%@author Mahdi Hosseini Moghaddam <m.hoseini.m@gmail.com> %%@doc Exercise 24 from "Exercises for programmers" Book %%@reference from <a href="http://erlang.blog.ir">مثال هایی در ارلنگ</a>, %% 2018 %%@copyright 2018 by Mahdi Hosseini Moghaddam %%@version 0.1 -module(ex24). -export([main/0]). -compile([debug_info]). main() -> try run() catch error:_Error -> io:format( "Please Enter only Numeric type~n"); throw:negativeNumber -> io:format( "Please Enter only non-zero positive number~n") end. run() -> {P,Q} = readItems(), A = isAnagram(P,Q), if A ==true -> io:fwrite("~s and ~s are anagram ~n", [P,Q]); true -> io:fwrite("~s and ~s are not anagram ~n", [P,Q]) end. %@ this function whether two strings have the same characters isAnagram(W1,W2) -> M1 = count_char(W1), M2 = count_char(W2), maps:keys(M2) =:= maps:keys(M1). count_char(Str) -> count_char(Str, #{}). %@ this function put the characters and numbers of their occurrence in a map count_char([H|T], X) -> case maps:is_key(H,X) of false -> count_char(T, maps:put(H,1,X)); true -> Count = maps:get(H,X), count_char(T, maps:update(H,Count+1,X)) end; count_char([], X) -> X. %@doc This function reads the user input the returns the result readItems() -> {ok,[P]} = io:fread( "Enter the First word: ","~s"), {ok,[Q]} = io:fread( "Enter the Second word: ","~s"), {P,Q}.