Created
September 23, 2014 13:52
-
-
Save lukesteensen/52640f3def5e0d5ef954 to your computer and use it in GitHub Desktop.
Elixir transducers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Transducers do | |
def map(f) do | |
fn(step) -> | |
fn(x, result) -> | |
step.(f.(x), result) | |
end | |
end | |
end | |
def filter(pred) do | |
fn(step) -> | |
fn(x, result) -> | |
if pred.(x) do | |
step.(x, result) | |
else | |
result | |
end | |
end | |
end | |
end | |
end | |
defmodule MyEnum do | |
def transduce(enum, init, transducer) do | |
reduce(enum, init, transducer.(&append/2)) | |
end | |
def reduce([], acc, _), do: acc | |
def reduce(enum, acc, f) do | |
[x | rest] = enum | |
reduce(rest, f.(x, acc), f) | |
end | |
defp append(x, arr) do | |
arr ++ [x] | |
end | |
end | |
add_one = fn x -> x + 1 end | |
odd? = fn x -> rem(x, 2) != 0 end | |
transducer = fn f -> | |
Transducers.map(add_one).(Transducers.filter(odd?).(f)) | |
end | |
arr = [1, 2, 3, 4, 5, 6] | |
IO.inspect MyEnum.transduce(arr, [], transducer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment