Last active
December 14, 2015 06:29
-
-
Save trigeek38/5042574 to your computer and use it in GitHub Desktop.
Here it is in Erlang :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(caesar). | |
-export[cipher/2]. | |
cipher(L, Shift) when is_list(L), is_integer(Shift), Shift =< 25, Shift >= -25 -> | |
%% Anonymous function with guards. | |
%% Strings are lists of numbers in Erlang [97,98,99] = [$a,$b,$c] = "abc" | |
%% We evaluat X and add it's shifted value to the head of the accumulator list Acc. | |
F = fun(X,Acc) when X + Shift > $z -> | |
[X + Shift - 26|Acc]; | |
(X,Acc) when X + Shift < $a -> | |
[X + Shift + 26|Acc]; | |
(X,Acc) -> | |
[X + Shift|Acc] | |
end, | |
lists:reverse(lists:foldl(F,[],L)). %% foldl is tail recursive, and lists:reverse is an optimized C BIF. | |
>>>>>> | |
Eshell V5.9.3.1 (abort with ^G) | |
1> c(caesar). | |
{ok,caesar} | |
2> caesar:cipher("cxyyblvhhe",7). | |
"jeffiscool" | |
3> caesar:cipher("jeffiscool",-7). | |
"cxyyblvhhe" | |
4> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment