官术网_书友最值得收藏!

Using the terminal to prototype and test ideas

The Elixir default installation provides an REPL (short for read-eval-print-loop) named IEx. IEx is a programming environment that takes user expressions, evaluates them, and returns the result to the user. This allows the user to test code and even create entire modules, without having to compile a source file.

To start prototyping or testing some ideas, all we need to do is use IEx via our command line.

Getting ready

To get started, we need to have Elixir installed. Instructions on how to install Elixir can be found at http://elixir-lang.org/install.html. This page covers installation on OSX, Unix and Unix-like systems, and Windows. It also gives some instructions on how to install Erlang, which is the only prerequisite to run Elixir.

How to do it…

To prototype and test the ideas using IEx, follow these steps:

  1. Start IEx by typing iex in your command line.
  2. Type some expressions and have them evaluated:
    iex(1)> a = 2 + 2
    4
    iex(2)> b = a * a
    16
    iex(3)> a + b
    20
    iex(4)>
    
  3. Define an anonymous function to add two numbers:
    iex(5)> sum = fn(a, b) -> a + b end
    Function<12.90072148/2 in :erl_eval.expr/5>
    
  4. Invoke the function to add two numbers:
    iex(6)> sum.(1,2)
    3
    
  5. Quit from IEx by pressing Ctrl + C twice.

How it works…

IEx evaluates expressions as they are typed, allowing us to get instant feedback. This allows and encourages experimenting ideas without the overhead of editing a source file and compiling it in order to see any changes made.

Note

In this recipe, we used the = operator. Unlike other languages, = is not an assignment operator but a pattern matching operator. We will get into more detail on pattern matching in the Using pattern matching and Pattern matching an HTTPoison response recipes in Chapter 2, Data Types and Structures.

In step 3, we used a dot (.) in the sum function right before the arguments, like this: sum.(1,2). The dot is used to call the anonymous function.

There's more…

It is possible to define modules inside an IEx session.

主站蜘蛛池模板: 纳雍县| 南乐县| 阿拉善左旗| 留坝县| 延津县| 兴海县| 高密市| 祥云县| 女性| 玉山县| 陆丰市| 华阴市| 会泽县| 隆回县| 剑阁县| 拜泉县| 敦煌市| 凤翔县| 井研县| 莲花县| 繁昌县| 邛崃市| 从化市| 沽源县| 上饶县| 湘潭县| 定结县| 海丰县| 南召县| 凌源市| 富川| 社旗县| 青川县| 黄冈市| 东安县| 顺义区| 响水县| 灌阳县| 永济市| 长葛市| 正阳县|