5
1

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 3 years have passed since last update.

逆にStreamを使う例題を作ってみよう!

5
Last updated at Posted at 2023-02-17

Streamを使うと、意外と簡単にできる。ということがあるのでは?
Streamですっきりと記述できる例題を書いてみます

思いついたら、増やしていきます。

ex01

  @doc """
  foo()が40を10回返すまで繰り返す

  ## 実行結果

      iex> Tutorial012.ex01
      :ok

  """

  def ex01() do
    Stream.repeatedly(fn  -> foo() end)
    |> Stream.filter(fn val -> val == 10 end)
    |> Stream.take(3)
    |> Stream.run()
  end

  defp foo() do
    Enum.take_random(0..10, 1)
    |> hd
    |> IO.inspect(label: "foo")
  end

ex02

  @doc """
  正の整数で3,5,7の倍数ではない数を小さいものから10個

  ## 実行結果

      iex> Tutorial012.ex02
      [1, 2, 4, 8, 11, 13, 16, 17, 19, 22]

  """
  def ex02() do
    Stream.iterate(1, &(&1 + 1))
    |> Stream.reject(fn val -> Integer.mod(val,3) == 0 end)
    |> Stream.reject(fn val -> Integer.mod(val,5) == 0 end)
    |> Stream.reject(fn val -> Integer.mod(val,7) == 0 end)
    |> Stream.take(10)
    |> Enum.to_list()
  end

ex03


  @doc """
  n回ごとにtrueを返すStreamから10個取り出す

  ## 実行結果

      iex> Tutorial012.ex03
      [false, false, true, false, false, true, false, false, true, false]

  """
  def ex03() do
    true_every(3)
    |> Stream.take(10)
    |> Enum.to_list()
  end

  defp true_every(n) when n > 0 do
    Stream.concat(Stream.duplicate(false, n-1), [true])
    |> Stream.cycle()
  end
5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?