SnellyCat
SnellyCat

Reputation: 155

Erlang - extract tuple from list of tuples

Hi first of all I'm a beginner regarding Erlang, I'm trying to extract a tuple from a list of tuples and assign it to a variable. Consider this dataset.

[{0,25075,-2},{0,0,-2},{0,376100,-4}] 

For example, I want to assign {0,25075,-2} to something like Var1 and so on.

I've tried the following in the shell for testing;

Tuples = [{0,25075,-2},{0,0,-2},{0,376100,-4}].
{Var1, Var2, Var3} = Tuples.

But I get this error;

ฐ** exception error: no match of right hand side value 
                    [{0,25075,-2},{0,0,-2},{0,376100,-4}]

Any help would be appreciated, thanks.

Upvotes: 2

Views: 1001

Answers (1)

zxq9
zxq9

Reputation: 13154

In the shell, if you have already assigned a value to a variable then you must clear the variable before reusing it. Use the command f(). to clear all current variables, or f(Var1). to just clear Var1.

Secondly, your syntax is wrong. It should be:

1> Tuples = [{0,25075,-2},{0,0,-2},{0,376100,-4}].
[{0,25075,-2},{0,0,-2},{0,376100,-4}]
2> [Var1, Var2, Var3] = Tuples.
[{0,25075,-2},{0,0,-2},{0,376100,-4}]
3> Var1.
{0,25075,-2}
4> Var2.
{0,0,-2}
5> Var3.
{0,376100,-4}
6> Var1 = "something else".
** exception error: no match of right hand side value "something else"
7> f(Var1).
ok
8> Var1 = "something else".
"something else"
9> Var1.
"something else"

You will not do assignments like this over lists very often, though, typically you will iterate and/or use list operations.

Upvotes: 2

Related Questions