Skip to content

Instantly share code, notes, and snippets.

@AndyDangerous
Created December 9, 2016 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndyDangerous/1773bd8f86aa3b5e5369977d4f26d94d to your computer and use it in GitHub Desktop.
Save AndyDangerous/1773bd8f86aa3b5e5369977d4f26d94d to your computer and use it in GitHub Desktop.
From the little elixir and OTP book. This exercise is about using `Stream` to do some lazy enumeration. The takeaway is that the _last_ enumerable thing has to be an enumerable.
defmodule StreamLines do
@path "./some_text.txt"
def large_lines!(path \\ @path) do
path
|> File.stream!
|> Stream.map(&String.replace(&1, "\n", ""))
|> Enum.filter(&(String.length(&1) > 70))
end
def lines_lengths!(path \\ @path) do
path
|> File.stream!
|> Enum.map(&String.length(&1))
end
def longest_line_length!(path \\ @path) do
path
|> File.stream!
|> Stream.map(&String.length(&1))
|> Enum.sort(&(&1 > &2))
|> hd
end
def longest_line!(path \\ @path) do
path
|> File.stream!
|> Stream.with_index
|> Stream.map(&({elem(&1, 0), String.length(elem(&1, 0)), elem(&1, 1)}))
|> Enum.sort(&(elem(&1, 1) > elem(&2, 1)))
|> hd
|> elem(0)
end
def words_per_line!(path \\ @path) do
path
|> File.stream!
|> Stream.map(&String.split(&1))
|> Enum.map(&(Enum.count(&1)))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment