Reputation: 2692
I'm learning Elixir, and one of the exercises I've decided to give myself is to try and write the Luhn algorithm for credit card validation in idiomatic Elixir.
I realize that ==
in Elixir is a Kernel function, which are apparently inlined by the compiler. Is there some kind of utility function that will let me do something like this?
...
|> == 0
instead of having to define a function to pipe into, as I've done here.
Elixir
defmodule Luhn do
def equalzero?(x) x == 0 end
def validate(num) do
digits = Integer.digits(num)
len = length digits
digits
|> Stream.with_index
|> Enum.reverse
|> Enum.reduce(0, fn {digit, index}, acc ->
if rem(len - index, 2) == 0 do
acc + digit * 2 |> Integer.digits |> Enum.sum
else
acc + digit
end
end)
|> rem(10)
|> Luhn.equalzero?
end
end
Upvotes: 1
Views: 226
Reputation: 222128
You can pipe into such operators (which are defined in Kernel
) by referring to their full path, Kernel.==
:
iex(1)> 0 |> Kernel.==(0)
true
iex(2)> 1 |> Kernel.==(0)
false
Upvotes: 4