Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Functions

livebook-sessions/functions.livemd

Functions

import IEx.Helpers

Named Functions

A function has three things

  1. Name of the module
  2. function name
  3. arguments
IO.puts("hello")

Capture

A function can be a data Its not executed yet

function = &IO.inspect/1
i function

As value

Enum.each(1..8, function)

Erlang

# can be used for coin flip etc
:random.uniform(2)
random_float_fn = &:random.uniform/0
random_float_fn.()
random_float_fn |> Stream.repeatedly() |> Enum.take(10)

Imports/Alias

import IEx.Helpers, only: [i: 1]
i &IO.puts/1

Anonymous Function

inc = fn x -> x + 1 end
i inc
inc.(42)
fun2 = &IO.inspect/1
i fun2
fun2.(42)
IEx.Helpers.h Enum.map/2
Enum.map(
  [1, 2, 3], 
  fn x -> 
    x * x 
  end)

Functions Capture

Intuition

fun = &(&1 + 1)
fun.(42)
i fun
fun2 = &(&1 + &2)
fun2.(42, 43)
fun3 = &(&1 + &1)
fun3.(4)

Performance

prefer:

fn item, list ->
  [item|list]
end

over:

&[&1|&2] 

Unless!!!

prefer:

&IO.inspect/1

over:

fn item -> IO.inspect(item)

Best Practice