Function Capturing

Function Capturing

These functional programming languages with their list generation and lazy evaluation make solving Project Euler Problems a real joy!

Find the sum of all the multiples of 3 or 5 below 1000.

1
2
-- haskell
sum [x | x <- [1..999], mod x 3 == 0 || mod x 5 == 0]
1
2
# elixir
1..999 |> Stream.filter(&(rem(&1,3) === 0 or rem(&1,5) === 0)) |> Enum.sum

noticed those pipes |> in elixir eh? yeah real nice!
here’s what it’d look like without pipes:

1
Enum.sum(Enum.filter(1..999,fn x -> rem(x,3) === 0 or rem(x,5) === 0 end))

noticed I used Enum instead of Stream this time? Yes it let’s you choose between Lazy and Eager evaluation.

where does the fn ... end come from? yeah this is how you define a lambda function, whereas in the first example I was using Function Capturing. Yeah .. haven’t seen it outside of elixir either.

Basically works like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# regular function inside a module
defmodule Math do
def square(x) do
x*x
end
end
IO.write Math.square(5)

# immediately invoked lambda function
IO.write (fn x -> x*x end).(5)

# Function capture
IO.write (&(&1*&1)).(5)

# outputs 252525

this makes it extremely comftie to pass as lambda :)