I. Records in Erlang A. motivation ------------------------------------------ WHY RECORDS? Tuples can store multiple, heterogenous data Compare: {"Northern Cardinal", "Cardinalis cardinalis" {8.3, 9.3, inch} } to: {species, common_name, "Northern Cardinal", scientific_name, "Cardinalis cardinalis" length, {min, 8.3, max, 9.3, unit, inch} } ------------------------------------------ Which is better? Why? Why have the atoms in positions 1, 2, 4, 6, and 8? ------------------------------------------ FUNCTIONS ON TUPLES species_common_name({Name,_,_,_}) -> Name. species_scientific_name({_,SN,_,_}) -> SN. measure_avg({Min,Max,Unit}) -> {Min+Max/2,Unit}. species_length({_,_,Len}) -> measure_avg(Len). ------------------------------------------ What happens if we change the order of some components in these tuples? What happens if we add new components to these tuples? ------------------------------------------ GOALS FOR RECORDS We would like to: - access data without knowing - pattern match against data without knowing ------------------------------------------ B. syntax 1. definition ------------------------------------------ RECORD DEFINITIONS ::= -record(, { }). ::= | , ::= | = ::= Examples: -record(measure, {min = 0.0, max, unit}). -record(bird, {common_name, scientific_name, length, wingspan}). ------------------------------------------ 2. creation ------------------------------------------ CREATION OF RECORD VALUES IN ERLANG % in measure.hrl -record(measure, {min = 0.0, max, unit}). #measure{min = 8.3, max = 9.3, unit = inch} In the Erlang shell need to use rr 1> rr("measure.hrl"). [measure] 2> CM = #measure{min = 8.3, max = 9.3, unit = inch}. #measure{min = 8.3,max = 9.3,unit = inch} Or if the records are in a module: 3> rr(birds). [bird,measure] ------------------------------------------ 3. access ------------------------------------------ FIELD ACCESS TO RECORDS Normally, use pattern matching: measure_avg(#measure{min = Min, max = Max}) -> (Min+Max)/2.0. Can also use access syntax (dot): CM#measure.min CM#measure.max ------------------------------------------