- A map to strore the data
- it’s like a map but has two advantages.
- The only thing I can put on struct is what I defined.
- It can not store any method (different to class), so it’s right under the map but with some constraints.
defmodule Identicon.Image do
defstruct hex: nil
end
%Identicon.Image{}
# it looks like a map, and it has the default keys (i.e. hex)
# And you can only add the registered keys.
Pattern matching Struct
- Goal: to get the first three elements of list from struct
defmodule Identicon do
def main(input) do
input
|> hash_input
|> pick_color
end
def pick_color(image) do
# red = image.hexa[0] # this sort of array accessing doesn't work in elixir.
%Identicon.Image{hex: hex_list} = image # pattern matching! pull of the list
# [r, g, b] = hex_list # doesn't work because much more hex numbers than 3
[r, g, b | _tail] = hex_list # _ means I don't care the remainder.
# if I put them in one line,
%Identicon.Image{hex: [r,g,b | _tail} = image
end
def hash_input(input) do
hex = :crypto.hash(:md5, input)
|> :binary.bin_to_list
%Identicon.Image{hex: hex}
end
end
Updating struct
defmodule Identicon.Image do
defstruct hex: nil, color: nil
end
defmodule Identicon do
def main(input) do
input
|> hash_input
|> pick_color
end
def pick_color(image) do
%Identicon.Image{hex: [r,g,b | _tail} = image
# image.color = {r,g,b} # don't do! it's js-script way
%Identicon.Image{image | color: {r, g, b}}
# Make a new struct taking all existing struct (image) and update (color)
end
#### Same function, but it uses the pattern matching of argument)
def pick_color(%Identicon.Image{hex: [r,g,b | _tail} = image ) do
%Identicon.Image{image | color: {r, g, b}}
end
def hash_input(input) do
hex = :crypto.hash(:md5, input)
|> :binary.bin_to_list
%Identicon.Image{hex: hex}
end
end