-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternMatching.ex
More file actions
79 lines (52 loc) · 1.48 KB
/
PatternMatching.ex
File metadata and controls
79 lines (52 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# Here :calendar is a module from Erlang(that's why is called as an atom)
# We are asking for the local_time, which is a TIMESTAMP a tuple with
# date and time, an each of those is a tuple.
{date, time} = :calendar.local_time
{year, month, day} = date
{hour, minute, second} = time
IO.puts "Year #{year}"
IO.puts "Month #{month}"
IO.puts "day #{day}"
IO.puts "Hour #{hour}"
IO.puts "Minute #{minute}"
IO.puts "Second #{second}"
# Reading a file
# This will not match if the file coannot be opened
# :ok will be replaced with :error, thus failing to match.
{:ok, contents} = File.read("my_files.txt")
IO.puts contents
# Patterns
# Ignoring date "_" is a special variable that matches
# everything that is sent to it but does not store anything.
{_, time} = :calendar.local_time
IO.puts elem(time, 2)
IO.puts "Capturing values"
Enum.each(Tuple.to_list(time), &IO.puts/1)
IO.puts "Finishing."
{_,{hour,_,_}} = :calendar.local_time
IO.puts hour
# Elixir will only bind a variable one time per bind
[a, a] = [1, 1]
# this will not pass
# [a, a] = [1, 2]
# this will not fail
a = 1
a = 2
# Variables bind once per match
# this will fail
# [a, b, a] = [1, 2, 3]
# [a, b, a] = [1, 1, 2]
# this will pass
[a, b, a] = [1, 2, 1]
# Working with pin operator
a = 2
[^a, a] = [2,3]
# This will fail, not because a is 2 but because it
# was rebound and the third element was not equal
# [a, b, a] = [1, 2, 3]
# [a, b, a] = [1, 1, 2]
a = 1 # No problem
# ^a = 2
^a = 1
^a = 2 - a # This will pass
IO.puts a