Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

October 24th, 2023

2023_10_24.livemd

October 24th, 2023

Side effects

defmodule M do
  def f(x) do
    2 * x
  end
end
x = 30
M.f(x)
x
x = 6000
M.f(x)
x = M.f(x)
x
IO.puts("1200")
2300
IO.puts("1200")
IO.puts("10")
IO.puts("200")
IO.puts("13200")
IO.puts("124400")
x = 10
y = 20
z = 30
x * y * z
IO.puts("2742893749")
x = IO.puts("x")
x

Immutability in lists

# range
1..100
100..1
1..100//2
even = Enum.to_list(10..50//2)
newlist = List.replace_at(even, 2, 13)
even
newlist

Function with side effects

defmodule SideEffects do
  def f(x) do
    IO.inspect(x)
    x
  end
end
SideEffects.f(10)
SideEffects.f({7_632_746, 234_234, :ok})
# IO.gets("Type a number: ")
# only on an elixir program or on iex

This is not a mathematical function!

Enum.random(even)

Exercise: Smallest and largest

defmodule Math do
  def smallest_largest([head | tail] = a_list) when is_list(a_list) do
    smallest_largest(tail, {head, head})
  end

  def smallest_largest(_),
    do: {:error, "!!! Wrong Argument !!! It should be a non-empty list !!!"}

  defp smallest_largest([], {smallest_so_far, largest_so_far}),
    do: {smallest_so_far, largest_so_far}

  defp smallest_largest([head | tail], {smallest_so_far, largest_so_far})
       when head > largest_so_far,
       do: smallest_largest(tail, {smallest_so_far, head})

  defp smallest_largest([head | tail], {smallest_so_far, largest_so_far})
       when head < smallest_so_far,
       do: smallest_largest(tail, {head, largest_so_far})

  defp smallest_largest([_head | tail], {smallest_so_far, largest_so_far}),
    do: smallest_largest(tail, {smallest_so_far, largest_so_far})
end
Math.smallest_largest([12, 34, 48, 48, 3])
Math.smallest_largest([1, -1, 100, 48, 3])