Skip to content

Instantly share code, notes, and snippets.

@jerel
Last active October 5, 2015 18:30
Show Gist options
  • Save jerel/28fc1fc0f56c0f9df3a0 to your computer and use it in GitHub Desktop.
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
# 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]
@danielberkompas
Copy link

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.

add.(2, 2)

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 an add variable. Otherwise, you'd need to always call named functions with (), like this:

add()

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

# colon on the left, then on the right. Does it execute something?
config :logger, :console, colors: [enabled: false]

This is the same as:

config(:logger, :console, [colors: [enabled: false]])

Which is itself shorthand for:

config(:logger, :console, [{:colors, [{:enabled, false}]}])

The colon in front like this colors: is syntactic sugar for a keyword list. So:

[key: value]

Is equivalent to:

[{:key, value}]

In function calls, if the last parameter is a keyword list, you can leave off the []. Hence this:

config :logger, :console, [colors: [enabled: false]]

Becomes this:

config :logger, :console, colors: [enabled: false]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment