1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

paiza.ioでelixirAdvent Calendar 2022

Day 16

paiza.ioでelixir その41

Last updated at Posted at 2022-11-04

概要

paiza.ioでelixirやってみた。
Agent使ってみた。

サンプルコード

defmodule FibAgent do
	def start_link do
		Agent.start_link(fn ->
			%{0 => 0, 1 => 1}
		end)
	end
	def fib(pid, n) when n >= 0 do
		Agent.get_and_update(pid, &do_fib(&1, n))
	end
	defp do_fib(cache, n) do
		case cache[n] do
			nil ->
				{n_1, cache} = do_fib(cache, n-1)
				result = n_1 + cache[n-2]
				{result, Map.put(cache, n, result)}
			cached_value ->
				{cached_value , cache}
		end
	end
end

{:ok, agent} = FibAgent.start_link()
IO.puts FibAgent.fib(agent, 10)


実行結果

55

成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?