Keys in Records

13 views
Skip to first unread message

Kurtis Rainbolt-Greene

unread,
Mar 8, 2012, 12:55:34 PM3/8/12
to magpi...@googlegroups.com
I've seen this example used in the guide, and used it in the REPL: `x: 1, y: 2, z: 3`

What exactly are `x`? I don't see any details about Atoms or Symbols in the guide, they're not strings as far as I can tell (even though the return for strings is the same: > "x" //=> x).

Also, how does one access the value of a key in a record? IE:

    var pair = x: 1, y: 2, z: 3
    // some code that returns the value associated to `x`

Bob Nystrom

unread,
Mar 13, 2012, 1:30:12 AM3/13/12
to magpi...@googlegroups.com
On Thu, Mar 8, 2012 at 9:55 AM, Kurtis Rainbolt-Greene
<kurtisrain...@gmail.com> wrote:
> I've seen this example used in the guide, and used it in the REPL: `x: 1, y:
> 2, z: 3`
>
> What exactly are `x`? I don't see any details about Atoms or Symbols in the
> guide, they're not strings as far as I can tell (even though the return for
> strings is the same: > "x" //=> x).

This is a great question! In Magpie parlance, a name immediately
followed by a ":" is a field. (Actually, now that I think about it,
data slots in classes are called fields too. Maybe we need an
unambiguous name here.)

Record fields aren't first class in Magpie, so they aren't symbols or
strings or anything. They are part of the grammar of the language
itself. They can appear in expressions to create a record, like:

var point = x: 1, y: 2

And they can appear in patterns to destructure a record, like:

var x: xcoord, y: ycoord = point

> Also, how does one access the value of a key in a record? IE:
>
>     var pair = x: 1, y: 2, z: 3
>     // some code that returns the value associated to `x`

Right now (and this is definitely a just-for-now thing) the only way
is by destructuring:

var x: a, y: b, z: c = pair

This will declare new variables "a", "b", and "c" and bind them to the
"x", "y", and "z" fields of pair. If you just want to pull out some of
the fields, you can do that too:

var x: a = pair

This will just pull out the "x" field and bind it to "a" while
ignoring the other fields.

- bob

Reply all
Reply to author
Forward
0 new messages