MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Conventional way of doing "struct"-like things?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg104523] Re: [mg104490] Conventional way of doing "struct"-like things?
  • From: danl at wolfram.com
  • Date: Tue, 3 Nov 2009 02:53:00 -0500 (EST)
  • References: <200911012255.RAA12068@smc.vnet.net>

> I find myself (as I'm sure everyone does) dealing with lists of
> structured data, e.g., a list of lists, each of which contains n
> elements with each entry representing a unique field.  What is the most
> conventional way to identify each of these elements when iterating over
> the whole list?  Obviously I can use [[...]]/Part, but I'm wondering if
> there's something considered more elegant.
>
> Take a concrete example where I have a CSV containing ZIP code data,
> with seven fields:  the zip code, latitude, longitude, city, state,
> county, and class.  What's the usual way of addressing this?  I can
> think of two obvious ones; just define symbolic names for the indices:
>
> data = Import[..., "CSV"];
>
> {ZIPCODE, LATITUDE, LONGITUDE, CITY, STATE, COUNTY, CLASS} = Range[7];
>
> ListPlot[{#[[LONGITUDE]], #[[LATITUDE]]} & /@ data,
>   PlotStyle -> PointSize[0.001]]
>
> or define functions (with or without the symbolic index names):
>
> latitude[x_] := x[[2]];
> longitude[x_] := x[[3]];
>
> ListPlot[{longitude[#], latitude[#]} & /@ data,
>   PlotStyle -> PointSize[0.001]]
>
> What's consider more in Mathematica's style, or is there something else
> more commonly used I'm not thinking of?
> [...]

I cannot say authoritatively what is "best practice" here. It tends to
vary  amongst different programmers and different needs.

I will point out that using definitions such as lattitude[x_] is a common
approach to making this not depend on internal details of your indexing. I
certainly would encourage that for anything larger than a small project.
Use of symbolic names for the indices can also help a bit to isolate low
level details from higher level code. Makes code packaging and 
maintainance much easier. Also makes it to a greater extent
self-documenting.

There may be other ways to go about this sort of code modularization that
either augment or avoid the ones you note, but if so I'm not seeing them
at the moment.

Daniel Lichtblau
Wolfram Research






  • Prev by Date: Re: Wrong Simplify[] Answer for Simplify[Cos[x]^4-Sin[x]^4]?
  • Next by Date: Re: Re: Opportunities and Player Pro
  • Previous by thread: Conventional way of doing "struct"-like things?
  • Next by thread: Re: Conventional way of doing "struct"-like things?