Last active
October 5, 2015 18:30
-
-
Save jerel/28fc1fc0f56c0f9df3a0 to your computer and use it in GitHub Desktop.
This is a rough list of things that might initially be confusing to a non-rubyist trying to learn Elixir
This file contains 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
# implicit return is fairly obvious but foreign to most languages | |
def foo(arg) do | |
arg | |
end | |
# foo/2 is the notation for a function that takes two arguments | |
# optional parenthesis | |
def foo arg, arg2 do | |
arg | |
end | |
# question marks | |
def foo(arg?) do | |
arg | |
end | |
# more question marks | |
def foo?(arg) do | |
arg | |
end | |
# here's an exclamation point | |
def foo!(arg) do | |
arg | |
end | |
# and a period | |
add.(2, 2) | |
# the underscore is a special write only variable | |
_ = 'test' | |
_ # ** (CompileError) iex:4: unbound variable _ | |
# when pipelining functions the first argument is implicit but you can still pass additional params! Example: | |
["test"] |> Enum.map(fn x -> String.upcase(x) end) | |
# colon on the left, then on the right. Does it execute something? | |
config :logger, :console, colors: [enabled: false] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great, thanks! Since it might be a while before I make an episode specifically on these things, let me clear a couple things up for you so you get your answer quickly.
Punctuation
? and ! can be part of variable and function names. They aren't special, but they do have conventional meanings.
? means that this variable is a boolean, or if it's a function, that it returns true or false.
! means that this function will throw an exception if something goes wrong, rather than doing something like returning an
{:error, reason}
tuple.Periods are only used to call anonymous functions.
They're ugly, but necessary so that Elixir can tell the difference between someone calling a named
add
function with no parentheses or simply referring to anadd
variable. Otherwise, you'd need to always call named functions with()
, like this:Elixir chose to allow you to call functions without parentheses, so it needs a way to distinguish between variables and calling anonymous functions. Hopefully that makes sense. 😄
Colons
This is the same as:
Which is itself shorthand for:
The colon in front like this
colors:
is syntactic sugar for a keyword list. So:Is equivalent to:
In function calls, if the last parameter is a keyword list, you can leave off the
[]
. Hence this:Becomes this: