Created
July 24, 2014 17:58
-
-
Save mroth/8d0b685df435d1409038 to your computer and use it in GitHub Desktop.
Pondering Elixir pipes
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
# A very common pattern in Elixir is to define a method that pipes the first | |
# argument through a series of transformations, for example here is some actual | |
# Elixir code I just wrote. | |
@spec encode(String.t) :: String.t | |
def encode(plaintext) do | |
plaintext | |
|> encipher | |
|> chunk | |
end | |
defp encipher(plaintext) do | |
plaintext | |
|> String.to_char_list | |
|> Enum.map(&encoder/1) | |
|> Enum.filter( &(&1) ) | |
end | |
defp chunk(ciphertext) do | |
ciphertext | |
|> Enum.chunk(5, 5, []) | |
|> Enum.join(" ") | |
end | |
# Repeating the argument variable seems redundant. | |
# | |
# What if a pipe operator had no lefthand value and was the first line of a | |
# method, it would automatically take the first argument of that method? | |
# | |
# This would allow the above to be rewritten as: | |
@spec encode(String.t) :: String.t | |
def encode(plaintext) do | |
|> encipher | |
|> chunk | |
end | |
defp encipher(plaintext) do | |
|> String.to_char_list | |
|> Enum.map(&encoder/1) | |
|> Enum.filter( &(&1) ) | |
end | |
defp chunk(ciphertext) do | |
|> Enum.chunk(5, 5, []) | |
|> Enum.join(" ") | |
end | |
# To me this actually seems more clear to read, since the method signature is | |
# directly above it's obvious what data you are operating on. It puts the focus | |
# even more clearly on the data transformation provided by the method. | |
# | |
# Is there a reason this can't work / shouldn't work this way? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment