2

I'm trying to execute sample code on the interactive shell from Armstrong's Erlang book. This is what the book says is the case:

1> Henry8 = #{ class => king, born => 1491, died => 1547 }. #{ born => 
1491, class=> king, died => 1547 }.
2> #{ born => B } = Henry8.
#{ born => 1491, class=> king, died => 1547 }.

However, this is what I'm getting on the shell, it seems the pattern matching is failing:

1> Henry8 = #{ class => king, born => 1491, died => 1547 }.
#{born => 1491,class => king,died => 1547}
2> #{ born => B } = Henry8.
* 1: illegal pattern
gboffi
  • 22,939
  • 8
  • 54
  • 85

2 Answers2

3

=> is for constructing a map. To pattern match a map, you need to use := instead.

1> Henry8 = #{ class => king, born => 1491, died => 1547 }.
#{born => 1491,class => king,died => 1547}
2> #{ born := B } = Henry8.
#{born => 1491,class => king,died => 1547}
3> B.
1491

This is documented in the section "Maps in Patterns" here.

Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

The code example was preceded by the text:

Pattern Matching the Fields of a Map
The := syntax we used in a map literal can also be used as a map pattern.

And that text was preceded by a whole section explaining the differences between => and := when constructing a map, so you should have been aware of the two different syntaxes.

In the book, line 2 of the example says:

2> #{born := B} = Henry8.

yet in the shell you typed:

2> #{ born => B } = Henry8.

I suggest you reread section 5.3 a little more carefully, and also read the pertinent section of LYSE, which includes this example:

1> Pets = #{"dog" => "winston", "fish" => "mrs.blub"}.
#{"dog" => "winston","fish" => "mrs.blub"}

2> #{"fish" := CatName, "dog" := DogName} = Pets.
#{"dog" => "winston","fish" => "mrs.blub"}

7> CatName.
"mrs.blub"

8> DogName.
"winston"

Here it's possible to grab the contents of any number of items at a time, regardless of order of keys. You'll note that elements are set with => and matched with :=. The := operator can also be used to update an existing key in a map

7stud
  • 46,922
  • 14
  • 101
  • 127