6
1

More than 3 years have passed since last update.

Enjoy Elixir #007 Flow

Last updated at Posted at 2020-07-14
1 / 8

はじめに

  • KFIEという近畿大学産業理工学部の情報系コミュニティがあります
  • 最近は、毎週火曜日にLT会をやっているそうです
  • 私が学生だったのはもうずいぶん昔のことなのですが、参加させてもらっています
  • 毎週、5分間時間をもらって、Elixirいいよ! を伝えていきたいとおもいます
  • 今日は以下を学びます
  • A journey of a thousand miles begins with a single step.
  • この記事はElixirを触るのがはじめてという方に向けて書いています

もくじ

001 mix new, iex -S mix, mix format
|> 002 型
|> 003 Pattern matching
|> 004 Modules and functions
|> 005 Pipe operator and Enum module
|> 006 HTTP GET!
|> 007 Flow
|> 008 AtCoderを解いてみる
|> 999 Where to go next


準備

$ mix new hello_flow
$ cd hello_flow

依存関係の解消

Flow allows developers to express computations on collections, similar to the Enum and Stream modules, although computations will be executed in parallel using multiple GenStages.

mix.exs
  defp deps do
    [
      {:flow, "~> 1.0"}
    ]
  end
$ mix deps.get

Flowをつかわずに単語の数を数えてみる

lib/word_count.ex
defmodule WordCount do
  @path "testfile.txt"

  def run do
    File.stream!(@path)
    |> Enum.flat_map(&String.split(&1, " "))
    |> Enum.map(&String.trim/1)
    |> Enum.reduce(%{}, fn word, acc ->
      Map.update(acc, word, 1, &(&1 + 1))
    end)
  end
end

実行

$ curl -o testfile.txt https://firebase.torifuku-kaiou.tokyo/testfile.txt

$ iex -S mix

iex> :timer.tc WordCount, :run, []
{21064536,
 %{
   "Russ" => 19354,
   "whole" => 18160,
   "prove" => 18346,
 ...
 }}

Flowを使って単語の数を数えてみる

lib/word_count.ex
defmodule WordCount do
  @path "testfile.txt"

  def run_with_flow do
    File.stream!(@path)
    |> Flow.from_enumerable()
    |> Flow.partition()
    |> Flow.flat_map(&String.split(&1, " "))
    |> Flow.map(&String.trim/1)
    |> Flow.reduce(fn -> %{} end, fn word, acc ->
      Map.update(acc, word, 1, &(&1 + 1))
    end)
    |> Enum.into(%{})
  end
end

実行

iex> recompile

iex> :timer.tc WordCount, :run_with_flow, []
{7952146,
 %{
   "Russ" => 19354,
   "whole" => 18160,
   "prove" => 18346,
 ...
 }}

iex> 7952146 / 21064536
0.37751346623538257
  • 処理時間が速くなっている:rocket::rocket::rocket:

Wrapping Up

  • 今日のポイントは、Flowを使うと速くなります
  • すごく乱暴にいいますけど、Enumで書いたプログラムをとにかくFlowと書き直す感じのお手軽さで速くなります
  • 次回は、AtCoderを解いてみます
    • 来週を待ちきれない方は、リソースやコミュニティの情報を Where to go next にまとめていますのでダイブしてください!
  • Enjoy!!!
6
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
6
1