This repository has been archived by the owner on Nov 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimplifier.ex
85 lines (64 loc) · 2.28 KB
/
Simplifier.ex
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
80
81
82
83
84
85
defmodule Expression.Simplifier do
def simplify(%Expression{identifier: identifier, type: type, args: args}) do
args = args |> Enum.map(&simplify(&1))
case type do
:operator ->
lhs = Enum.at(args, 0)
rhs = Enum.at(args, 1)
if is_number(lhs) and is_number(rhs) do
Expression.evaluate(Expression.new(lhs, identifier, rhs))
else
case identifier do
:times ->
cond do
# 0 * x = 0 and x * = 0
lhs === 0 or rhs === 0 -> 0
# 1 * x = x
lhs === 1 -> rhs
# x * 1 = x
rhs === 1 -> lhs
true -> %Expression{identifier: identifier, type: type, args: args}
end
:divided_by ->
cond do
# 0 / x = 0
lhs == 0 -> 0
# x / 1 = x
rhs == 1 -> lhs
true -> %Expression{identifier: identifier, type: type, args: args}
end
:plus ->
cond do
# 0 + x = x
lhs == 0 -> rhs
# x + 0 = x
rhs == 0 -> lhs
true -> %Expression{identifier: identifier, type: type, args: args}
end
:minus ->
cond do
rhs == 0 -> lhs
true -> %Expression{identifier: identifier, type: type, args: args}
end
:raised_to ->
cond do
# x^1 = x
rhs === 1 -> lhs
# x ^ 0 = 1
rhs === 0 -> 1
# 1^x = 1
lhs === 1 -> 1
# 0^x = 0
lhs === 0 -> 0
true -> %Expression{identifier: identifier, type: type, args: args}
end
_ -> %Expression{identifier: identifier, type: type, args: args}
end
end
:function -> %Expression{identifier: identifier, type: type, args: args}
end
end
def simplify(a) do
a
end
end