Last active
July 11, 2018 05:37
-
-
Save aesmail/a9b08b596acdd0c0be2d90da75e6cb6b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyModule do | |
# this is valid sytax. However, you can't access x and my_function inside `def` | |
x = 2 | |
my_function = fn (x) -> x * 2 end | |
# this is valid syntax. It will replace @my_variable with 2 anywehre inside the module at compile time. | |
@my_variable 2 | |
# the following line will not compile | |
# because only the following values are supported here: | |
# lists, tuples, maps, atoms, numbers, bitstrings, PIDs and remote functions in the format &Mod.fun/arity | |
@my_function fn (x) -> x * 2 end # compile error | |
# now for the good code that will do what you intend: | |
def first() do | |
# this function will return an anonymous function | |
fn (a) -> a * 2 end | |
end | |
def second() do | |
double = first() # now 'double' is the anonymous function which we defined inside of first() | |
IO.puts double.(4) # this will print 8 | |
third(double) | |
end | |
def third(f) do | |
IO.puts f.(10) # we passed the anonymous function as a parameter, so f is like double, this will print 20 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment