Skip to content

Instantly share code, notes, and snippets.

@gboyegadada
Forked from squarism/multiline.exs
Created March 25, 2024 15:27
Show Gist options
  • Save gboyegadada/f42c6a0ee62fda0f576f09b5ada12c22 to your computer and use it in GitHub Desktop.
Save gboyegadada/f42c6a0ee62fda0f576f09b5ada12c22 to your computer and use it in GitHub Desktop.
Multiline Anonymous Functions in Elixir
# Examples of Different Styles and Syntax
# legal / positive case / you can do these stuffs
# ---------------------------------------------------------------------------
# single line, nothing special
Enum.map(0...2, fn i -> IO.puts i end)
"""
0
1
2
"""
# ... but what if we want to do something more complicated?
# I want to do two things while I count to three.
Enum.map(0..2, fn i -> IO.write "-> "; IO.puts i end)
"""
-> 0
-> 1
-> 2
"""
# the semicolon is ok I guess since the above lines are sort of horizontally related because of the output
# but we could also do something like this
Enum.map(0..2, fn i ->
IO.puts "I'm working on:"
IO.puts i
IO.puts ""
end)
"""
I'm working on:
0
I'm working on:
1
I'm working on:
2
"""
# yes you could do a shorter newline IO.puts, I'm just trying to show multi-line here
# illegal / negative cases / you can't do these stuffs
# ---------------------------------------------------------------------------
iex> Enum.map(0..9, fn(e) { IO.write i } end)
# ** (SyntaxError) iex:24: syntax error before: '{'
# you can do this but why am I putting the braces as if it's a ruby block
iex> Enum.map(0..9, fn(e) -> { IO.write e } end)
# 0123456789
# ok great but maybe I want some more readability
# let's define a module
defmodule App do
def print_inline(number), do: IO.write number
end
# well that doesn't help us too much, I still need an anonymous function
Enum.map(0..9, fn e -> App.print_inline(e) end)
0123456789
# and I really need to have a function for Enum.map
Enum.map(0..9) |> App.print_inline
# ** (UndefinedFunctionError) function Enum.map/1 is undefined or private.
# this can't work, it won't know a few things
# well this is as close as we can get
Enum.map(0..9, &App.print_inline/1)
# 0123456789
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment