Skip to content

Instantly share code, notes, and snippets.

@javiervidal
Last active March 8, 2017 13:31
Show Gist options
  • Save javiervidal/f9fb220054ec67b42f6bd630661d4cbc to your computer and use it in GitHub Desktop.
Save javiervidal/f9fb220054ec67b42f6bd630661d4cbc to your computer and use it in GitHub Desktop.
Anonymous functions
fizz_buzz = fn
(0,0,_) -> "FizzBuzz"
(0,_,_) -> "Fizz"
(_,0,_) -> "Buzz"
(_,_,a) -> a
end
IO.puts fizz_buzz.(0,0,"foo")
IO.puts fizz_buzz.(0,"foo","bar")
IO.puts fizz_buzz.("foo",0,"bar")
IO.puts fizz_buzz.("foo","bar","Atlas")
handle_open = fn
{:ok, file} -> "First line: #{IO.read(file, :line)}"
{_, error} -> "Error: #{:file.format_error(error)}"
end
IO.puts handle_open.(File.open("existent")) # call with a file that exists
IO.puts handle_open.(File.open("nonexistent")) # and then with one that doesn't
prefix = fn
prefix_string -> fn
name -> "#{prefix_string} #{name}"
end
end
mrs = prefix.("Mrs")
IO.puts mrs.("Smith")
IO.puts prefix.("Elixir").("Rocks")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment