Skip to content

Commit cafc64b

Browse files
author
Bernard Pietraga
committed
Add exercise 1 from chapter 22
1 parent 1a0b89b commit cafc64b

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
.DS_Store
2+
erl_crash.dump

chapter_22/protocols_1.exs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
defprotocol CaesarSalad do
2+
def encrypt(string, shift)
3+
def rot13(string)
4+
end
5+
6+
defimpl CaesarSalad, for: List do
7+
def encrypt(list, shift), do:
8+
list |> Enum.map(&encrypt_char(&1, shift))
9+
10+
def rot13(list), do:
11+
encrypt(list, 13)
12+
13+
def encrypt_char(char, shift) when char in 97..122, do:
14+
97 + rem(char + shift - 97, 26)
15+
def encrypt_char(char, shift) when char in 65..90, do:
16+
65 + rem(char + shift - 65, 26)
17+
def encrypt_char(char = 32, _shift), do:
18+
char
19+
end
20+
21+
defimpl CaesarSalad, for: BitString do
22+
def encrypt(string, shift) do
23+
String.to_char_list(string)
24+
|> CaesarSalad.List.encrypt(shift)
25+
|> List.to_string
26+
end
27+
28+
def rot13(string), do:
29+
encrypt(string, 13)
30+
end
31+
32+
ExUnit.start
33+
34+
defmodule CaesarSaladTest do
35+
use ExUnit.Case
36+
37+
test "list implementation" do
38+
expected = CaesarSalad.rot13("Space rocket")
39+
assert expected == "Fcnpr ebpxrg"
40+
end
41+
42+
test "string implementation" do
43+
expected = CaesarSalad.rot13("Elixir rocks")
44+
assert expected == "Ryvkve ebpxf"
45+
end
46+
end

0 commit comments

Comments
 (0)