fp
Section
list = [1, 2, 3, 4]
List.delete_at(list, -1)
Enum.map(["dogs", "cats", "flowers"], &String.upcase/1)
defmodule StringList do
def upcase([]), do: []
def upcase([first | rest]), do: [String.upcase(first) | upcase(rest)]
end
StringList.upcase(["dogs", "cats", "flowers"])
Body recursion
defmodule FactorialBR do
def of(0), do: 1
def of(n) when n > 0, do: n * of(n - 1)
end
FactorialBR.of(5)
Tail Recursion
defmodule FactorialTR do
def of(n), do: factorial_of(n, 1)
defp factorial_of(0, acc), do: acc
defp factorial_of(n, acc) when n > 0, do: factorial_of(n - 1, n * acc)
end
FactorialTR.of(5)
Screw Factory
defmodule ScrewFactory do
def run(pieces) do
pieces
|> Stream.chunk_every(50)
|> Stream.flat_map(&add_thread/1)
|> Stream.chunk_every(100)
|> Stream.flat_map(&add_head/1)
|> Enum.each(&output/1)
end
defp add_thread(pieces) do
Process.sleep(50)
Enum.map(pieces, &(&1 <> "--"))
end
defp add_head(pieces) do
Process.sleep(100)
Enum.map(pieces, &("0" <> &1))
end
defp output(screw) do
IO.inspect(screw)
end
end
metal_pieces = Enum.take(Stream.cycle(["-"]), 1000)
ScrewFactory.run(metal_pieces)
metal_pieces = Enum.take(Stream.cycle(["-"]), 1000)
ScrewFactory.run(metal_pieces)