Why are NamedTuples and (immutable) structs separate?
Asked Answered
H

2

7

Can someone explain why NamedTuples and immutable structs are separate instead of NamedTuples being an anonymous struct like there are anonymous functions function (x) x^2 end? They look like they have the same structure conceptually (I would also like to know if they have a different memory layout), though they have different methods to access their fields (example below). It seems very plausible to implement the NamedTuple methods for structs, but I may just not be aware of a good reason not to do that.

struct X; a; b; c; end

Xnt = NamedTuple{(:a,:b,:c), Tuple{Any, Any, Any}}

t1 = (10, 20.2, 30im)
#
#
# t1[1]          indexing by position
# t1[1:2]        slicing
# for el in t1   iteration

x1 = X(t1...)
# x1.a           getting field

xnt1 = Xnt(t1)
# xnt1.a         getting field
# xnt1[:a]       indexing by field
# xnt1[1]        indexing by position
#
# for el in t1   iteration
Hu answered 28/9, 2021 at 23:36 Comment(0)
A
13

Every single NamedTuple instance with the same names and field types is of the same type. Different structs (types) can have the same number and type of fields but are different types.

Amin answered 29/9, 2021 at 1:5 Comment(3)
Good point, the struct name, perhaps as a Symbol, becomes a distinguishing parameter. Then we can consider a concrete NamedTuple type as equivalent to a struct with nothing for a name.Hu
Essentially, nominal vs. structural subtyping.Everrs
Thanks @phipsgabler, the search terms "nominal vs structural type system" led to interesting reads and put this answer in the context of language design.Hu
K
1

A named tuple has names for each column in the tuple. Named tuples are an alternative to a dataframe. When instantiating the namedTuple, you pass the list of field names as a list. Named tuples create a specification contract for expected fields and reduce the chance of code breaking.

Kore answered 1/10, 2021 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.