Hommer Smith
Hommer Smith

Reputation: 27852

Iterate over range in Elixir to call a function with those numbers

I have the following code in Elixir:

fizzbuzz = fn
  0, 0, _ -> "FizzBuzz"
  0, _, _ -> "Fizz"
  _, 0, _ -> "Buzz"
  _, _, c -> c
end

calc_fizzbuzz = fn n -> fizzbuzz.(rem(n, 3), rem(n, 5), n) end
IO.puts calc_fizzbuzz.(10) # Buzz
IO.puts calc_fizzbuzz.(11) # 11
IO.puts calc_fizzbuzz.(12) # Fizz
IO.puts calc_fizzbuzz.(13) # 13
IO.puts calc_fizzbuzz.(14) # 14
IO.puts calc_fizzbuzz.(15) # FizzBuzz
IO.puts calc_fizzbuzz.(16) # 16

And I want to be able to avoid repeating myself, so I'm trying to do something like:

(10..16) |> fn(n) -> IO.puts(calc_fizzbuz.(n)) end

But this is not working. How am I supposed to do this in ?

Upvotes: 0

Views: 2095

Answers (2)

Adam Millerchip
Adam Millerchip

Reputation: 23091

Obligatory comprehensions version:

iex> for n <- 10..16, do: calc_fizzbuzz.(n)
["Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16]

With printing:

iex> (for n <- 10..16, do: calc_fizzbuzz.(n)) |> Enum.each(&IO.puts/1)
Buzz
11
Fizz
13
14
FizzBuzz
16
:ok

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

One cannot pipe to an anonymouse function. Also, you want to pipe values, one by one, not the whole range, so you need an iterator there.

Use function capture &/1:

Enum.each(10..16, &IO.puts(calc_fizzbuzz.(&1)))

or

10..16
|> Enum.map(calc_fizzbuzz)
|> Enum.each(&IO.inspect/1)

Upvotes: 4

Related Questions