Whenever you need a key-value store, maps are the “go to” data structure in Elixir. A map is created using the
Compared to keyword lists, we can already see two differences:
- Maps allow any value as a key.
- Maps’ keys do not follow any ordering.
In contrast to keyword lists, maps are very useful with pattern matching. When a map is used in a pattern, it will always match on a subset of the given value:
As shown above, a map matches as long as the keys in the pattern exist in the given map. Therefore, an empty map matches all maps.
Variables can be used when accessing, matching and adding map keys:
The Map module provides a very similar API to the
Keyword module with convenience functions to manipulate maps:
Maps have the following syntax for updating a key’s value:
The syntax above requires the given key to exist. It cannot be used to add new keys. For example, using it with the
:c key failed because there is no
:c in the map.
When all the keys in a map are atoms, you can use the keyword syntax for convenience:
Another interesting property of maps is that they provide their own syntax for accessing atom keys:
Elixir developers typically prefer to use the
map.field syntax and pattern matching instead of the functions in the
Map module when working with maps because they lead to an assertive style of programming. This blog post by José Valim provides insight and examples on how you get more concise and faster software by writing assertive code in Elixir.
Nested data structures
Often we will have maps inside maps, or even keywords lists inside maps, and so forth. Elixir provides conveniences for manipulating nested data structures via the
update_in/2 and other macros giving the same conveniences you would find in imperative languages while keeping the immutable properties of the language.
Imagine you have the following structure:
We have a keyword list of users where each value is a map containing the name, age and a list of programming languages each user likes. If we wanted to access the age for john, we could write:
It happens we can also use this same syntax for updating the value:
update_in/2 macro is similar but allows us to pass a function that controls how the value changes. For example, let’s remove “Clojure” from Mary’s list of languages:
There is more to learn about
update_in/2, including the
get_and_update_in/2 that allows us to extract a value and update the data structure at once. There are also
get_and_update_in/3 which allow dynamic access into the data structure.
This concludes our introduction to associative data structures in Elixir. You will find out that, given keyword lists and maps, you will always have the right tool to tackle problems that require associative data structures in Elixir.
The Object class defines three equality-test methods: ==, eql?, and equal?. At the Object level, all equality-test methods do the same thing: they tell you whether two objects are exactly the same object. Here they are in action:
All three of the positive equality-test methods give the same results in these examples: when you test a against a, the result is true, and when you test a against b, the result is false. (The not-equal or negative equality test method != is the inverse of the == method; in fact, if you define ==, your objects will automatically have the != method.) We have plenty of ways to establish that a is a but not b.
But there isn’t much point in having three tests that do the same thing.
Further down the road, in classes other than Object, == and/or eql? are typically redefined to do meaningful work for different objects. For example, String redefines == and eql? to return whether the value of the strings being compared are identical. Two strings can have the same value but in fact be different objects. The equal? method retains its Object definition and checks if two strings are exactly the same object. Let’s look at string equality in action:
As you can see, the strings are == and eql?, but not equal?. Ruby recommends against redefining equal? so that it can always be used to determine object identity.
Why do we have == and eql? if they’re synonymous at the Object level? Because it gives us more flexibility as we subclass Object. Because we don’t redefine equal?, we have the option to redefine either == or eql? and compare objects in different ways.
For example, in the Numeric class (a superclass of Integer and Float), == performs type conversion before making a comparison but eql? doesn’t:
Ruby gives you a suite of tools for object comparisons, and not always just comparison for equality.
Trying to remember a method name or just discover what you can call on an object? Ruby has you covered! Check out examples below
List all methods
List all direct methods except Object class methods
List all direct methods ( not comming from a parent class )
List all instance methods
List all direct instance methods
List all methods and then grep on them
In Go it’s idiomatic to communicate errors via an explicit, separate return value. This contrasts with the exceptions used in languages like Java and Ruby and the overloaded single result / error value sometimes used in C. Go’s approach makes it easy to see which functions return errors and to handle them using the same language constructs employed for any other, non-error tasks
By convention, errors are the last return value and have type error, a built-in interface.
errors.New constructs a basic error value with the given error message.
A nil value in the error position indicates that there was no error.
It’s possible to use custom types as errors by implementing the Error() method on them. Here’s a variant on the example above that uses a custom type to explicitly represent an argument error.
In this case we use &argError syntax to build a new struct, supplying values for the two fields arg and prob.
The two loops below test out each of our error-returning functions. Note that the use of an inline error check on the if line is a common idiom in Go code.
If you want to programmatically use the data in a custom error, you’ll need to get the error as an instance of the custom error type via type assertion.
See this great post on the Go blog for more on error handling.
A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.
Proc objects are closures, meaning they remember and can use the entire context in which they were created.
There are several methods to create a Proc
- Use the Proc class constructor:
- Use the Kernel#proc method as a shorthand of ::new:
- Receiving a block of code into proc argument (note the &):
- Construct a proc with lambda semantics using the Kernel#lambda method (see below for explanations about lambdas):
*Use the Lambda literal syntax (also constructs a proc with lambda semantics):
Lambda and non-lambda semantics
- Procs are coming in two flavors: lambda and non-lambda (regular procs). Differences are:
- In lambdas, return means exit from this lambda;
*In regular procs, return means exit from embracing method (and will throw LocalJumpError if invoked outside the method);
*In lambdas, arguments are treated in the same way as in methods: strict, with ArgumentError for mismatching argument number, and no additional argument processing;
*Regular procs accept arguments more generously: missing arguments are filled with nil, single Array arguments are deconstructed if the proc has multiple arguments, and there is no error raised on extra arguments
Lambdas are useful as self-sufficient functions, in particular useful as arguments to higher-order functions, behaving exactly like Ruby methods.
Procs are useful for implementing iterators:
Inside map, the block of code is treated as a regular (non-lambda) proc, which means that the internal arrays will be deconstructed to pairs of arguments, and return will exit from the method test. That would not be possible with a stricter lambda.
You can tell a lambda from a regular proc by using the lambda? instance method.
Lambda semantics is typically preserved during the proc lifetime, including &-deconstruction to a block of code:
The only exception is dynamic method definition: even if defined by passing a non-lambda proc, methods still have normal semantics of argument checking.
This exception ensures that methods never have unusual argument passing conventions, and makes it easy to have wrappers defining methods that behave as usual.
subscribe via RSS