Elixir basics · Lesson 01 (open contents)
Let the code speak
Open IEx, enter an expression, and tell code, results, and errors apart.
Copy into IEx and press Enter after each line
Run one line at a time. Guess the result before you press Enter.
# An addition expression returns a number
2 + 3
# A function call returns new text
String.upcase("cat")
# IO.puts prints a line on the screen
IO.puts("Hello, BEAM")2 + 3returns5.String.upcase("cat")returns"CAT".IO.puts("Hello, BEAM")prints the text, then IEx shows:ok. For now, read it as a “done” label.
Read from the first line down
- In
2 + 3,+adds the numbers on its left and right. String.upcase("cat")gives the string to theupcasefunction in theStringmodule.IO.puts("Hello, BEAM")creates two visible results: the printed text and the return value:okshown by IEx.
Symbols are not secret signs
iexEnter this in a terminal to open IEx.
iex>This is the prompt. Enter only the code after it. Do not copy the prompt.
#This line is a comment. Elixir does not run it.
Match each name to its meaning
IEx
Short for Interactive Elixir. It is like scratch paper for trying one or two lines of code.
expression
Code that produces a value when it runs. A number, an operation, or a function call can all be expressions.
return value
The result an expression gives back when it finishes. It does not always print a sentence.
Why these forms are useful
IEx is Elixir's interactive window. You enter a small piece of code, and it answers at once. You do not need a project or a long list of commands yet.
An expression is code that produces a result. 2 + 3 produces 5. String.upcase("cat") produces "CAT".
When you see an error, pause. Read the last few lines. Look for a name the computer does not know or data that does not fit. An error is not a lost point. It is another kind of result.
Close the answer and try
Ask IEx to multiply 7 by 6, then turn beam into uppercase text.
# Replace the question mark with an operator
7 ? 6
# Finish the function name
String.____("beam")Target result: First you should see 42, then "BEAM".
Stuck? Read one hint
Multiplication uses *. The function that made text uppercase was upcase.
After you run it, see one answer
# The star means multiplication
7 * 6
# upcase returns a new uppercase string
String.upcase("beam")Think about it: Is `iex>` part of the code?
No. It is the prompt IEx shows while it waits for your code.
Remember these three lines
- 1
IEx is useful for trying very short Elixir code.
- 2
An expression produces a value when it runs.
- 3
Read what an error says, then change only one thing.