-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapter6.exs
78 lines (55 loc) · 1.65 KB
/
chapter6.exs
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
# ModulesAndFunctions-1, ModulesAndFunctions-3
defmodule Times do
def double(n) do
n * 2
end
def triple(n) do
n * 3
end
def quadruple(n) do
double(n) + double(n)
end
end
# ModulesAndFunctions-2
# iex chapter6_function_calls_and_pattern_matching.exs
# or
# iex> c "chapter6_function_calls_and_pattern_matching.exs"
defmodule MyModule do
# ModulesAndFunctions-4
def sum(0), do: 0
def sum(n), do: n + sum(n-1)
# ModulesAndFunctions-5
def gcd(x, 0), do: x
def gcd(x, y), do: gcd(y, rem(x, y))
end
IO.puts "Sum from 1 to 10 is #{MyModule.sum(10)}"
IO.puts "Greatest Common Divisor of 45 and 105 is #{MyModule.gcd(45, 105)}"
# ModulesAndFunctions-6
defmodule Chop do
def guess(number, left..right) when number == left or number == right do
IO.puts "#{number}"
end
def guess(number, left..right) when number > left and number < right do
middle = div(left+right, 2)
IO.puts "Is it #{middle}"
if number >= middle do
guess(number, middle..right)
else
guess(number, left..middle)
end
end
end
Chop.guess(273, 1..1000)
# ModulesAndFunctions-7
# convert float to string with 2 decimals (Erlang)
:erlang.float_to_list(223.44456, decimals: 2)
# get value of operating system environment variable (Elixir)
System.get_env("PWD")
# return extension component of a file name (Elixir)
Path.extname("dave/test.exs")
# return the process's current working directory (Elixir)
System.cwd()
# convert a string containing JSON into Elixir data structures
# e.g. https://github.com/devinus/poison library
# execute a command in your operating system's shell
System.cmd("whoami", [])