-7.1 C
New York
Thursday, February 20, 2025

Introduction to Elixir: a brand new model of practical programming



To print this we will use the IO.examine Operate for lovely impression:


IO.examine(book_lengths)
(17, 12, 9, 9, 21)

Elixir assortment sorts

We’ve already seen the Checklist Write the motion. Elixir contains these fundamental kinds of assortment:

  • Checklist: A homogeneous assortment of immutable arbitrary sorts, however designed to switch in duplication.
    • Syntax: sq. helps with articles: (x,y,z)
  • Tupla: Designed to keep up values ​​primarily, non -manipulation, tuples are like lists however oriented to studying efficiency. Take into consideration them a kind of information entry compilation.
    • Syntax: Orthopedic gadgets with components: {x,y,z}
  • Key phrase record: Key-value pairs, chain solely keys, primarily used for arguments named for capabilities
    • Syntax: sq. helps with friends: {x: x1,y: y1,z: z1}
  • Maps: Household key worth pairs, the place the keys could be something and the gathering is messy.
    • Syntax: Share of orthopedic gadgets curly with friends:
      • %{x => x1, y => y1, z => z1}
      • %{x: x1, y: y1, z: z1}

Maps and atoms

The maps have two declaration types, and the one which should be used is determined by whether or not the keys are atoms. A atom It’s a variable whose worth is identical as its identify, a type of tremendous fixed. An atom is said with a colon adopted by a literal.

We might create a series saved map at entire values ​​as so:


books_and_lengths = %{ "The Bhagavad Gita" => 17, "Tao Te Ching" => 12 }

The next is completely different and creates a map of atoms to integers, in all probability not what we would like on this case:


books_and_lengths = %{ "The Bhagavad Gita": 17, "Tao Te Ching": 12 }

Take note of the location of the colon. In MapThe colon is instantly subsequent to the Kay signifies that it’s an atom, and the atoms could be locked (to assist unlawful characters in one other method).

The conclusion is to make use of the arrow syntax (=>) While you need a regular variable and the important thing and the colon (:) While you need atoms.

Usually, atoms are declared like this:


:my_atom

Right here is one other option to declare a map with atom keys:


my_map = %{:atom1 => “foo”, :atom2 => “bar”}

Modules

Elixir admits modules, that are areas of names that meet associated capabilities. Does No Hold the state or variables as a category or code block. As anticipated, you possibly can name different capabilities inside the identical module, however people who name from overseas must favor the calls or import the module.

Right here is a straightforward module:


defmodule BookFunctions do
  def myFunc
  finish
finish

BookFunctions.myFunc()

Patterns coincidence

Syntactic flavors and the traits of the usual library contribute largely to compensate for the final sensation of utilizing a language. They’re the frequent traits with which it interacts on a regular basis. However every language has some traits that stand out.

The coincidence of practical patterns is a classy and charming attribute that Elixir brings to the desk, which permits him to execute the conditional operate in a syntax much like the swap. For instance we need to emit small, medium or lengthy in line with the lengths of the guide titles:


defmodule BookFunctions do
  def categorize_length(size) do
    case size do
      size when size <= 10 -> "Quick"
      size when size &lt= 20 -> "Medium"
      _ -> "Lengthy"
    finish
  finish

  def print_categories(lengths) do
    Enum.every(lengths, fn size ->
      class = categorize_length(size)
      IO.places("#{size} characters: #{class}")
    finish)
  finish
finish

A few notes:

  • BookFunctions It’s a module, which you’ve gotten seen.
  • In elixir, return statements are implicit, so the categorize_length() The operate mechanically returns no matter the results of the final expression.

He case The key phrase is what the patterns coincidence block creates, within the categorize_length operate. He size when size syntax (technically, a Safety clause) permits us to confirm the vary of the size variable, and if it meets the factors, the -> The operator tells us what to return the case. (Since that is the ultimate assertion of the operate, it should even be the practical return worth).

We might use this new operate in our book_lengths So:


BookBookFunctions.print_categories(book_lengths)
17 characters: Medium
12 characters: Medium
9 characters: Quick
9 characters: Quick
21 characters: Lengthy

Enum.every It’s analogous to forEach In different languages ​​resembling JavaScript, permitting us to carry out an operation in every factor of a set.

Loop

Elixir No have and whereas loops. This generally is a bit surprising at the start, however it’s consistent with immutability favored by practical philosophy. In essence, Elixir doesn’t need you to make mutations throughout the loops, and as a substitute desires you to make use of the recursion. Recursion retains it within the subject of capabilities, and ideally, you need to use pure capabilities (which means, capabilities with out negative effects).

A lot of the loop you will need to do could be dealt with with practical operations resembling Enum.every and Enum.map. Elixir discussion board It has a very good and intensive dialogue about loops and options.

Comprehension

One of the crucial direct methods of simulating a for is with understandings, which might be forgiven by complicated with an actual loop:


for x <- 0..10, do: IO.places x

See Elixir’s paperwork For extra details about understandings and the way they simplify assortment operations.

Pipe operator

The pipe operator offers you a clear syntax for the outcomes of the chain operate. Give it some thought as a extra elegant type of nesting capabilities. Right here is a straightforward instance of the pipe operator in our books_and_lengths assortment:


books_and_lengths
  |> Map.keys() 
  |> Enum.map(&String.upcase/1) 
  |> Enum.be part of(", ") 
  |> IO.places() 

The exit is:


The Bhagavad Gita, Tao Te Ching

Concurrence

Though the concurrence is a posh concern, it’s considered one of Elixir’s drive areas, so we take a fast look. Elixir makes use of actors, one thing like digital threads by which they aren’t full processes of the working system. The actors admit the previous of messages for simplified concurrent communication.

The next instance, Demonstrating messagesIt’s from Elixir’s paperwork:


defmodule Instance do
  def pay attention do
    obtain do
      {:okay, "hey"} -> IO.places("World")
    finish

    pay attention()
  finish
finish

Notice that pay attention The operate is recursive (it calls itself on the finish), which lets you deal with a number of messages. With out recursion, the method would come out.

To launch this actor, we use spawn:


pid = spawn(Instance, :pay attention, ())

Then we will ship a message from the primary course of, utilizing the pid We save:


ship pid, {:okay, "hey"}

This results in the “world” to the console.

Conclusion

Languages ​​are largely outlined by what they facilitate and what they make troublesome. Elixir is clearly devoted to facilitating a programmer to stay within the practical programming mentality, and harder to deviate in mutations and negative effects.

The overall impact is that it tends to put in writing a very good practical programming code, supplied that it really works with language and doesn’t struggle it. It’s not troublesome to see why Elixir has captured a lot curiosity, bringing Erlang’s legacy to the trendy world. It’s a programming language with robust concepts about tips on how to do issues and an lively and enthusiastic neighborhood.


Related Articles

Latest Articles