COP 4020 Lecture -*- Outline -*- * Records in Erlang ** 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} } ------------------------------------------ See birdtuples.erl Q: Which is better? the second one is easier to follow Q: Why? the information Q: Why have the atoms in positions 1, 2, 4, 6, and 8? to help us remember what those positions mean To deal with tuples we might do the following... ------------------------------------------ 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). ------------------------------------------ See birdtuples.erl Q: What happens if we change the order of some components in these tuples? (some) functions break! Q: What happens if we add new components to these tuples? All the functions break! Try adding wingspan to the records in birdtuples.erl ------------------------------------------ GOALS FOR RECORDS We would like to: - access data without knowing - pattern match against data without knowing ------------------------------------------ ... the order of the components ... all the components (or how many there are). ** syntax *** definition ------------------------------------------ RECORD DEFINITIONS ::= -record(, { }). ::= | , ::= | = ::= Examples: -record(measure, {min = 0.0, max, unit}). -record(bird, {common_name, scientific_name, length, wingspan}). ------------------------------------------ *** 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] ------------------------------------------ See also birds.erl *** 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 ------------------------------------------ See also birds.erl